Groovy problem with great accuracy

given the following line

BigDecimal step = 10.0G**-1.0G

groovy 1.7.5 returns incorrect

0.1000000000000000055511151231257827021181583404541015625

and groovy 1.8 returns the correct

0.1

Unfortunately, I want to solve my problem in Grails. 1.4 with groovy 1.8 is not yet stable enough (controllers are not updated in dev mode), and grails 1.3.7 comes with groovy 1.7.x

two questions:

  • Am I doing something wrong or is this a bug in 1.7.5?

  • How can I avoid this behavior? I, although BigDecimals, where is ideal for this kind of rounding problem?

second update: (forget about the first update) -

Now I'm a little confused. It seems that I get different results every time I try ....:

BigDecimal step = 10.0G**-1.0G
println step

returns 0.1000000000000000055511151231257827021181583404541015625

and

println 10.0G**-1.0G

returns

0.1

in both versions of groovy.

BigDec step = 10.0G**-1.0G groovyConsole , groovy. , - groovyConsole.

toString, .

, ...

def step = 10.0G**-1.0G

Double...

, :

  • a) BigDecimal?

  • b) BigDecimal, ?

Thanx

+3
4

, . java-:

BigDecimal (double val)            BigDecimal, .

  • , , , , BigDecimal.
  • Double to BigDecimal
  • 0.1000000000000000055511151231257827021181583404541015625, double 0.1
  • println 10.0G**-1.0G (0.1)
  • BigDecimal step = 10.0G**-1.0G; println step BigDecimal 0.1,

, groovy ( BigDecimals), groovyConsole.

+4

Groovy 1.7.5 10.0G**-1.0G 0.1

JDK ?

+2

, 10.0G ** - 1.0G Math.pow(10, -1), math.pow double, . , -1, (1.0G/10.0G).

However, I don’t know Groovy, so my hunch may be wrong, but that is certainly what it looks like, and this is backed up by what the documents say for Groovy.

+1
source

If you want to convert from Double to BigDecimal and not get all the extra digits, one way to do this is to put Double in String and then convert it to BigDecimal, which will prevent all extra digits from appearing from the exact binary representation of the double.

Double someFraction = 1.23456789
BigDecimal sameFraction = "${someFraction}".toBigDecimal()
+1
source

All Articles