#295·decimal

String Trim Trailing Zeros bool variable

Author: vasilbekkCreated Oct 1, 2022Updated Dec 25, 2025

About

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

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

go
{"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:

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

Need:

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

Like a MarshalJSONWithoutQuotes var:

go
// 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.