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
Why the difference beteween using
Float.SetFloat64()
andFloat.SetString()
?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.