I have occurred in this strange division error in a grails project (But I think grails has little to do with it, is a groovy or java question I think):
If in the groovy console I run this
float money = -1.30
float r = 0.01
println ((money/r).class.name)
println ((money/r).floatValue())
println ((money/r).toString() )
I get this output
java.lang.Double
-130.0
-129.99999813735482
The float division in groovy give me a Double, and this is correct but
why the Double toString() give me a so strange value “-129.99999813735482” and
not the correct “-130.0”?
As everyone says,
doubleandfloataren’t precise enough for what you’re trying to do.One solution is to not use
floatas your object type, and do:As you can see, Groovy uses
BigDecimal, which means the output is: