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

String Trim Trailing Zeros bool variable #295

Open
vasilbekk opened this issue Oct 1, 2022 · 0 comments · May be fixed by #296
Open

String Trim Trailing Zeros bool variable #295

vasilbekk opened this issue Oct 1, 2022 · 0 comments · May be fixed by #296

Comments

@vasilbekk
Copy link

vasilbekk commented Oct 1, 2022

About

As default .String() trunc zeroes:
1.00 -> "1"
2.00 -> "2"

If we set MarshalJSONWithoutQuotes = false, in JSON we'll get:

{"decimal": Decimal{1.00}} -> {"decimal": 1}
{"decimal": Decimal{2.00}} -> {"decimal": 2}
{"decimal": Decimal{2.01}} -> {"decimal": 2.01}

I think we need to add varibale StringTrimTrailingZeros, because in .String() true contsant:

func (d Decimal) String() string {
	return d.string(true)
}

Need:

func (d Decimal) String() string {
	return d.string(StringTrimTrailingZeros)
}

Like a MarshalJSONWithoutQuotes var:

// MarshalJSON implements the json.Marshaler interface.
func (d Decimal) MarshalJSON() ([]byte, error) {
	var str string
	if MarshalJSONWithoutQuotes {
		str = d.String()
	} else {
		str = "\"" + d.String() + "\""
	}
	return []byte(str), nil
}

Motivation

By default, when decimal is output as a string (for example, in JSON), zeros are truncated from it (2.00 -> 2, 3.11 -> 3.11, 13.000 -> 13). But this logic can be changed by this variable.

For example, if you have numeric(10,2) values stored in your database, and you want your API response to always be given 2 decimal places (even 2.00, 3.00, 17.00 [not 2,3,17]), then this variable is a great way out.

@vasilbekk vasilbekk linked a pull request Oct 1, 2022 that will close this issue
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

Successfully merging a pull request may close this issue.

1 participant