File tree 7 files changed +92
-0
lines changed
7 files changed +92
-0
lines changed Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
1
+ module float
2
+
3
+ go 1.16
4
+
5
+ require github.com/shopspring/decimal v1.2.0 // indirect
Original file line number Diff line number Diff line change
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 =
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ func main () {
4
+ float ()
5
+ bigFloat ()
6
+ shopspringDecimal ()
7
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments