I am using github.com/shopspring/decimal for money operations (Numbers with precision)
What is the best way to marshalling a decimal.Decimal and unmarshallin and get the same value ?
Is a way to convert decimal.Decimal to string ?
Thank.
I am using github.com/shopspring/decimal for money operations (Numbers with precision)
What is the best way to marshalling a decimal.Decimal and unmarshallin and get the same value ?
Is a way to convert decimal.Decimal to string ?
Thank.
2
Answers
decimal.Decimal
implements thejson.Marshaler
interface and thejson.Unmarshaler
interface.json.Marshal()
calls itsMarshalJSON
method to produce JSON; whilejson.Unmarshal()
calls itsUnmarshalJSON
method to parse the JSON-encoded data. So, you do not need to do it explicitly.decimal.Decimal
implements theStringer
interface.Therefore, to convert to a string, where
d
is adecimal.Decimal
:To obtain a
decimal.Decimal
from a string, usedecimal.NewFromString()
:Note also that
decimal.Decimal
will marshal to JSON as astring
by default (that is, a double-quoted representation). Unmarshalling automatically supports quoted (string) or non-quoted (number) values.The marshalling behaviour can be controlled by setting
decimal.MarshalJSONWithoutQuotes
totrue
if desired. e.g. if interacting with an API that requires/expects a number value in a JSON payload.There are two things to be aware of here:
this setting affects the marshalling of all
decimal.Decimal
values. There appears to be no way to marshal with/without quotes on a case-by-case basis selectivelymarshalling without quotes may result in a silent loss of precision
There is no need to "control" the unmarshalling behaviour. a
decimal.Decimal
will be unmarshalled from either a (correctly encoded)string
ornumber
value, as needed.There is no loss of precision resulting from unmarshalling a
number
(aside from any loss occurring as a result of the original marshalling to that number value).