From 161f04f87dddc8fe55e408f603b33065d638f733 Mon Sep 17 00:00:00 2001 From: Chad Skeeters Date: Mon, 4 Nov 2024 08:45:51 -0600 Subject: [PATCH] Adds MarshalYAML for marshaling yaml Adds MarshalYAMLWithoutQuotes for marshaling Decimal without quotes --- decimal.go | 23 +++++++++++++++++++++++ go.mod | 2 ++ 2 files changed, 25 insertions(+) diff --git a/decimal.go b/decimal.go index a37a230..3caf091 100644 --- a/decimal.go +++ b/decimal.go @@ -25,6 +25,7 @@ import ( "regexp" "strconv" "strings" + "gopkg.in/yaml.v3" ) // DivisionPrecision is the number of decimal places in the result when it @@ -65,6 +66,14 @@ var PowPrecisionNegativeExponent = 16 // silently lose precision. var MarshalJSONWithoutQuotes = false +// MarshalYAMLWithoutQuotes should be set to true if you want the decimal to +// be YAML marshaled as a number, instead of as a string. +// WARNING: this is dangerous for decimals with many digits, since a YAML +// unmarshallers may unmarshal a YAML numbers as an IEEE 754 +// double-precision floating point number, which means you can potentially +// silently lose precision. +var MarshalYAMLWithoutQuotes = false + // ExpMaxIterations specifies the maximum number of iterations needed to calculate // precise natural exponent value using ExpHullAbrham method. var ExpMaxIterations = 1000 @@ -1790,6 +1799,20 @@ func (d Decimal) MarshalJSON() ([]byte, error) { return []byte(str), nil } +// MarshalYAML implements the yaml.Marshaler interface. +func (d Decimal) MarshalYAML() (interface{}, error) { + if MarshalYAMLWithoutQuotes { + n := yaml.Node{ + Kind: yaml.ScalarNode, + Style: yaml.TaggedStyle, // yaml_PLAIN_SCALAR_STYLE == TaggedStyle + Value: d.String(), + } + return n, nil + } + + return d.String(), nil +} + // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation // is already used when encoding to text, this method stores that string as []byte func (d *Decimal) UnmarshalBinary(data []byte) error { diff --git a/go.mod b/go.mod index 3d26474..2f15ed2 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/shopspring/decimal go 1.10 + +require gopkg.in/yaml.v3 v3.0.1 // indirect