英文:
marshalling decimal.Decimal in golang
问题
我正在使用github.com/shopspring/decimal进行货币操作(带有精度的数字)
最佳方法是如何将decimal.Decimal进行编组和解组,并获得相同的值?
有没有一种将decimal.Decimal转换为字符串的方法?
谢谢。
英文:
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.
答案1
得分: 2
decimal.Decimal
实现了 json.Marshaler
接口和 json.Unmarshaler
接口。json.Marshal()
调用它的 MarshalJSON
方法来生成 JSON;而 json.Unmarshal()
调用它的 UnmarshalJSON
方法来解析 JSON 编码的数据。因此,你不需要显式地进行这些操作。
英文:
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.
答案2
得分: 2
decimal.Decimal
实现了 Stringer
接口。
因此,要将 decimal.Decimal
转换为字符串,其中 d
是 decimal.Decimal
:
s := d.String()
要从字符串中获取 decimal.Decimal
,请使用 decimal.NewFromString()
:
d, err := decimal.NewFromString(s)
if err != nil {
// 处理错误
}
还要注意,默认情况下,decimal.Decimal
将作为一个字符串(即双引号表示)进行 JSON 编组。解组时自动支持带引号(字符串)或不带引号(数字)的值。
如果需要,可以通过将 decimal.MarshalJSONWithoutQuotes
设置为 true
来控制编组行为,例如与需要在 JSON 载荷中使用数字值的 API 进行交互。
这里有两个需要注意的事项:
1)此设置会影响所有 decimal.Decimal
值的编组。似乎没有办法有选择地按情况设置带引号或不带引号的编组。
2)不带引号的编组可能导致精度的悄悄丢失。
不需要“控制”解组行为。根据需要,decimal.Decimal
将从正确编码的字符串或数字值解组。
从解组到数字时,不会丢失精度(除非在原始编组为该数字值时发生了任何丢失)。
英文:
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:
-
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 -
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论