Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds MarshalYAML for marshaling yaml #387

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"regexp"
"strconv"
"strings"
"gopkg.in/yaml.v3"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"gopkg.in/yaml.v3"
"gopkg.in/yaml.v3"

)

// DivisionPrecision is the number of decimal places in the result when it
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1790,6 +1799,20 @@ func (d Decimal) MarshalJSON() ([]byte, error) {
return []byte(str), nil
}

// MarshalYAML implements the yaml.Marshaler interface.
cskeeters marked this conversation as resolved.
Show resolved Hide resolved
func (d Decimal) MarshalYAML() (interface{}, error) {
cskeeters marked this conversation as resolved.
Show resolved Hide resolved
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 {
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/shopspring/decimal

go 1.10

require gopkg.in/yaml.v3 v3.0.1 // indirect