douyingbei1458 2015-12-28 04:23
浏览 264

Go-货币计算

I am trying to do monetary calculations with Go.

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.

First I used 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)

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.

Instead, when using 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)

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

My questions are

  1. Why the difference beteween using Float.SetFloat64() and Float.SetString()?

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

Thanks in advance, and forgive my English.

[EDIT]

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.

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

  • 写回答

3条回答 默认 最新

  • dongtan7639 2015-12-28 09:02
    关注

    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.

    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. Never use floats for currency. Really.

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

    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数