Skip to content

Parsing and encoding

JSON

A Decimal can be used directly as a struct field. MarshalJSON always writes a quoted string, so JSON parsers in other languages don't read the value as a floating-point number. UnmarshalJSON accepts quoted and unquoted numbers, and the JSON literal null leaves the Decimal unchanged.

type Order struct {
    Price udecimal.Decimal `json:"price"`
    Qty   udecimal.Decimal `json:"qty"`
}

b, _ := json.Marshal(Order{Price: udecimal.MustParse("12.50"), Qty: udecimal.MustParse("3")})
fmt.Println(string(b))

// quoted and unquoted numbers both decode
var o Order
err := json.Unmarshal([]byte(`{"price": 12.5, "qty": "3"}`), &o)
fmt.Println(o.Price, o.Qty, err)
// Output:
// {"price":"12.5","qty":"3"}
// 12.5 3 <nil>

Decoding uses the same rules as Parse, including the parse mode.

Databases

Decimal implements sql.Scanner and driver.Valuer. Value stores the decimal as a string. Scan accepts string, []byte, int, int32, int64, uint64 and float64, and returns an error for nil. For nullable columns, use NullDecimal; its Value returns nil when Valid is false.

var a, b udecimal.NullDecimal
_ = a.Scan("1.23")
_ = b.Scan(nil)

fmt.Println(a)
fmt.Println(b)
// Output:
// {1.23 true}
// {0 false}
fmt.Println(udecimal.NullDecimal{Decimal: udecimal.MustParse("1.2345"), Valid: true}.Value())
fmt.Println(udecimal.NullDecimal{}.Value())
// Output:
// 1.2345 <nil>
// <nil> <nil>

Parsing

fmt.Println(udecimal.Parse("1234567890123456789.1234567890123456789"))
fmt.Println(udecimal.Parse("-1234567890123456789.1234567890123456789"))
fmt.Println(udecimal.Parse("-0.00007890123456789"))

// error cases
fmt.Println(udecimal.Parse("0.12345678901234567890123"))
fmt.Println(udecimal.Parse(""))
fmt.Println(udecimal.Parse("1.123.123"))

// Output:
// 1234567890123456789.1234567890123456789 <nil>
// -1234567890123456789.1234567890123456789 <nil>
// -0.00007890123456789 <nil>
// 0 precision out of range. Only support maximum 19 digits after the decimal point
// 0 can't parse empty string
// 0 invalid format: can't parse '1.123.123'

Parse accepts:

  • an optional sign, + or -
  • one or more digits
  • optionally, a . followed by one or more digits, up to the default precision (19 unless changed)
  • at most 200 characters in total
Input Result
+1.5 1.5
007.50 7.5
.5, -.5, 1., + ErrInvalidFormat
1e5 ErrInvalidFormat; scientific notation isn't supported
"" ErrEmptyString
201 characters or more ErrMaxStrLen

MustParse works like Parse but panics on error.

Parse modes

By default, input with more decimal places than the default precision returns an error (ParseModeError). If your data has more decimal places and losing them is acceptable, use ParseModeTrunc, which truncates the extra digits:

fmt.Println(udecimal.Parse("0.12345678901234567890123"))

udecimal.SetDefaultParseMode(udecimal.ParseModeTrunc)
defer udecimal.SetDefaultParseMode(udecimal.ParseModeError)

fmt.Println(udecimal.Parse("0.12345678901234567890123"))
// Output:
// 0 precision out of range. Only support maximum 19 digits after the decimal point
// 0.1234567890123456789 <nil>

The parse mode (ParseMode) applies to the whole package: Parse, MustParse and the text decoders (UnmarshalJSON, UnmarshalText and Scan). Set it once at startup. SetDefaultParseMode panics for any value other than ParseModeError or ParseModeTrunc.

Text, query strings and binary

MarshalText and UnmarshalText use the same format as String and Parse, without quotes. EncodeValues lets go-querystring encode a Decimal field as a string.

MarshalBinary writes a compact binary form:

fmt.Println(udecimal.MustParse("1.23").MarshalBinary())
fmt.Println(udecimal.MustParse("-1.2345").MarshalBinary())
fmt.Println(udecimal.MustParse("1234567890123456789.1234567890123456789").MarshalBinary())
// Output:
// [0 2 11 0 0 0 0 0 0 0 123] <nil>
// [1 4 11 0 0 0 0 0 0 48 57] <nil>
// [0 19 19 9 73 176 246 240 2 51 19 211 181 5 249 181 241 129 21] <nil>

The layout is [flags] [prec] [total length] [coefficient bytes]: one flag byte for the sign and for whether the coefficient is stored as math/big, the precision, the total length in bytes, and the coefficient in big-endian order. A 128-bit coefficient takes 8 bytes, or 16 if it doesn't fit in 64 bits. UnmarshalBinary returns ErrInvalidBinaryData for data that doesn't follow this layout.

Interfaces

Interface Methods Format
json.Marshaler, json.Unmarshaler MarshalJSON, UnmarshalJSON quoted string, for example "1.23"
encoding.TextMarshaler, TextUnmarshaler, TextAppender MarshalText, UnmarshalText, AppendText plain string, for example 1.23
encoding.BinaryMarshaler, BinaryUnmarshaler, BinaryAppender MarshalBinary, UnmarshalBinary, AppendBinary compact binary (see above)
sql.Scanner, driver.Valuer Scan, Value string
go-querystring query.Encoder EncodeValues string