奇怪的浮动除法结果

奇怪的浮动除法结果

本文介绍了奇怪的浮动除法结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




$ $ $ $ $ $ $ $浮动$ -1.30
浮动r = 0.01

println((money / r).class.name)
println((money / r).floatValue())
println((money / r).toString())

我得到这个输出

           



一个解决方案是不使用 float 作为你的对象类型,并做:

  def money = -1.30 
def r = 0.01

println (money / r).class.name)
println((money / r).floatValue())
println((money / r).toString())

正如你所看到的,,这意味着输出是:

  java.math.BigDecimal 
-130.0
-130


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 butwhy the Double toString() give me a so strange value "-129.99999813735482" andnot the correct "-130.0"?

解决方案

As everyone says, double and float aren't precise enough for what you're trying to do.

One solution is to not use float as your object type, and do:

def money = -1.30
def r = 0.01

println ((money/r).class.name)
println ((money/r).floatValue())
println ((money/r).toString() )

As you can see, Groovy uses BigDecimal, which means the output is:

java.math.BigDecimal
-130.0
-130

这篇关于奇怪的浮动除法结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:11