Skip to content

Commit 3884d59

Browse files
committed
added float
1 parent 874aa03 commit 3884d59

File tree

7 files changed

+92
-0
lines changed

7 files changed

+92
-0
lines changed

float/README.md

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Comparing float implementations and JSON serialization
2+
3+
## input
4+
5+
`1234567890123456.87`
6+
7+
## output
8+
9+
```
10+
float64: {"price":1234567890123456.8}
11+
big.Float: {"price":"1.2345678901234568e+15"}
12+
shopspring/decimal.Decimal: {"price":"1234567890123456.87"}
13+
```

float/big_float.go

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"math/big"
7+
)
8+
9+
type BigFloat struct {
10+
Price *big.Float `json:"price"`
11+
}
12+
13+
func bigFloat() {
14+
v := BigFloat{
15+
Price: big.NewFloat(1234567890123456.87),
16+
}
17+
18+
b, _ := json.Marshal(v)
19+
20+
fmt.Println("big.Float:", string(b))
21+
}

float/float.go

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
)
7+
8+
type Float struct {
9+
Price float64 `json:"price"`
10+
}
11+
12+
func float() {
13+
v := Float{
14+
Price: 1234567890123456.87,
15+
}
16+
17+
b, _ := json.Marshal(v)
18+
19+
fmt.Println("float64:", string(b))
20+
}

float/go.mod

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
module float
2+
3+
go 1.16
4+
5+
require github.com/shopspring/decimal v1.2.0 // indirect

float/go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
2+
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=

float/main.go

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package main
2+
3+
func main() {
4+
float()
5+
bigFloat()
6+
shopspringDecimal()
7+
}

float/shopspring_decimal.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
7+
"github.com/shopspring/decimal"
8+
)
9+
10+
type ShopspringDecimal struct {
11+
Price decimal.Decimal `json:"price"`
12+
}
13+
14+
func shopspringDecimal() {
15+
p, _ := decimal.NewFromString("1234567890123456.87")
16+
17+
v := ShopspringDecimal{
18+
Price: p,
19+
}
20+
21+
b, _ := json.Marshal(v)
22+
23+
fmt.Println("shopspring/decimal.Decimal:", string(b))
24+
}

0 commit comments

Comments
 (0)