decimal icon indicating copy to clipboard operation
decimal copied to clipboard

Why is the json serialization a string and not a float type。

Open fulldog opened this issue 1 year ago • 7 comments

Can you provide an api to let the consumer decide which types to serialize?

fulldog avatar Jul 17 '23 09:07 fulldog

The network transmission of strings is more accurate, and there will be no overflow.

weizihua avatar Jul 22 '23 14:07 weizihua

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
}

dgunay avatar Aug 09 '23 19:08 dgunay

Just set decimal.MarshalJSONWithoutQuotes = true

iambudi avatar Aug 20 '23 02:08 iambudi

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.

mwoss avatar Dec 30 '23 15:12 mwoss

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

fulldog avatar Jan 03 '24 02:01 fulldog

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?

mwoss avatar Jan 08 '24 21:01 mwoss

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

fulldog avatar Jan 10 '24 06:01 fulldog