decimal
decimal copied to clipboard
Why is the json serialization a string and not a float type。
Can you provide an api to let the consumer decide which types to serialize?
The network transmission of strings is more accurate, and there will be no overflow.
You can accomplish this by creating a small wrapper type:
type Dollars struct{ decimal.Decimal }
func NewDollars() Dollars {
return Dollars{decimal.New(0, 0)}
}
func (d Dollars) MarshalJSON() ([]byte, error) {
bytes, err := d.Decimal.MarshalJSON()
if err != nil {
return nil, err
}
// remove the quotes since we want it to be a JSON number
return bytes[1 : len(bytes)-1], nil
}
Just set decimal.MarshalJSONWithoutQuotes = true
Thank you all for helping @fulldog! As @iambudi mentioned please use MarshalJSONWithoutQuotes
variable to specify whether you want to serialize Decimal to string or a floating number. Be careful tho, floats are not designed to precisely represent every number, also there is no guarantee the float representation on one system will be identical to that on the other.
The network transmission of strings is more accurate, and there will be no overflow.
I know the string doesn't overflow, but many third-party apis specify the type
Do you think the documentation of MarshalJSONWithoutQuotes
is not explicit enough and we should extend it, so it's more clear for new library users?
Do you think the documentation of
MarshalJSONWithoutQuotes
is not explicit enough and we should extend it, so it's more clear for new library users?
I don't think I can use global variables because I only want to use them in a specific api. Global variables may affect serialization of other api json