skip to Main Content

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


  1. decimal.Decimal implements the json.Marshaler interface and the json.Unmarshaler interface. json.Marshal() calls its MarshalJSON method to produce JSON; while json.Unmarshal() calls its UnmarshalJSON method to parse the JSON-encoded data. So, you do not need to do it explicitly.

    Login or Signup to reply.
  2. decimal.Decimal implements the Stringer interface.

    Therefore, to convert to a string, where d is a decimal.Decimal:

    s := d.String()
    

    To obtain a decimal.Decimal from a string, use decimal.NewFromString():

    d, err := decimal.NewFromString(s)
    if err != nil {
        // handle err
    }
    

    Note also that decimal.Decimal will marshal to JSON as a string 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 to true 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:

    1. 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 selectively

    2. marshalling 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 or number 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search