Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
fulldog opened this issue Jul 17, 2023 · 8 comments
Open

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

fulldog opened this issue Jul 17, 2023 · 8 comments

Comments

@fulldog
Copy link

fulldog commented Jul 17, 2023

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

@weizihua
Copy link

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

@dgunay
Copy link

dgunay commented Aug 9, 2023

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
}

@iambudi
Copy link

iambudi commented Aug 20, 2023

Just set decimal.MarshalJSONWithoutQuotes = true

@mwoss
Copy link
Member

mwoss commented Dec 30, 2023

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.

@fulldog
Copy link
Author

fulldog commented Jan 3, 2024

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

@mwoss
Copy link
Member

mwoss commented Jan 8, 2024

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?

@fulldog
Copy link
Author

fulldog commented Jan 10, 2024

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

@LukaGiorgadze
Copy link

can we avoid global variables?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants