Go-货币计算 [英] Go - monetary calculations

查看:91
本文介绍了Go-货币计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Go进行货币计算.

I am trying to do monetary calculations with Go.

环顾标准库,似乎可以使用 big/math .
而且我运行了一些代码来检查其工作原理.

Looking around the standard library, big/math seems to be the one I can make use of.
And I ran some codes to check how it works.

首先,我使用了 Float.SetFloat64()

var f = 18.9
var f2 = 1.65
bf := new(big.Float)
bf.Add(bf, new(big.Float).SetFloat64(f))
bf.Add(bf, new(big.Float).SetFloat64(f2))
result, _ := bf.Float64()
fmt.Println(result)

这给了我结果: 20.549999999999997
就像 float64 类型的计算一样.
由于我在处理金钱,因此结果必须为 20.55 .

This gives me the result: 20.549999999999997
Just like the calculation with float64 type.
Since I'm dealing with money, the result must be 20.55.

相反,当使用 Float.SetString()

var s = fmt.Sprintf("%f", 18.9)
var s2 = fmt.Sprintf("%f", 1.65)
bf := new(big.Float)
bf2, _ := new(big.Float).SetString(s)
bf3, _ := new(big.Float).SetString(s2)
bf.Add(bf, bf2)
bf.Add(bf, bf3)
result, _ := bf.Float64()
fmt.Println(result)

这给了我结果: 20.55
SEEMs我可以将其用于我的目的(但我不确定..).

This gives me the result: 20.55
It SEEMs I can use this for my purpose (but I am not sure..).

我的问题是

  1. 为什么使用 Float.SetFloat64() Float.SetString()之间的区别?

使用 Float.SetString()进行货币计算时是否有陷阱?

Are there any pitfalls when using Float.SetString() for monetary calculations?

预先感谢,请原谅我的英语.

Thanks in advance, and forgive my English.

我知道应该避免使用浮点数类型来表示货币价值.
但是类型的选择实际上不受我控制.

I know float types should be avoided for representing money value.
but the choice of the type is not really under my control..

我想知道以上两个问题中的一个(或两个)的答案.

I want to know the answers to either(or both) of the above two questions.

或者 Float.SetString()给我看似正确的结果的原因也很有帮助.

Or the reason why Float.SetString() gives me the seemingly correct results is also helpful.

推荐答案

从不,永远不要将float用作货币.这是一种不精确的类型,因此您最终不得不四舍五入计算,最终到处到处损失(或赚钱)一分钱.您可能认为可以,但是您的会计师可以告诉您它不是.您必须准确无误.

Never, ever, never use float for currency. Its an imprecise type, so you end up having to round calculations off and you end up losing (or gaining) a penny here and there. You may think that's ok but your accountant will be able to tell you its not. You have to be perfectly accurate.

因此,可以使用专用的任意精度十进制类型,也可以使用整数并保留便士(或便士的分数)并适当地显示它.(就像您自1970年以来以秒为单位保存日期,但将其显示为dd-mm-yyyy一样).

So either use an specialised arbitrary-precision decimal type, or use an integer and hold pennies (or fractions of a penny) and display it appropriately. (just like how you hold dates as seconds since 1970, yet display them as dd-mm-yyyy).

PS.切勿将浮点数用作货币.真的.

PS. Never use floats for currency. Really.

PPS.不要将浮动货币用作货币,永远不要永远.

PPS. Do not use floats for currency, not ever never ever.

这篇关于Go-货币计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆