Fun with java/bigdecimal vs ruby

Hi,

one of my colleagues was unhappy today about decimal accuracy for even
simple operations in a pure java environment…

So I tried to reproduce this with jruby in an interactive session.
Here it is :slight_smile:

irb(main):001:0> require ‘java’
true
irb(main):002:0> java.math.BigDecimal.new(1.2).to_s
“1.1999999999999999555910790149937383830547332763671875”
irb(main):003:0> java.math.BigDecimal.new(1.1+0.1).to_s
“1.20000000000000017763568394002504646778106689453125”

Now, I’m curious: how could I get with jruby the ‘machine’ binary
representation of these java BigDecimal results ?

TIA


Christian

Problem is with the input, not the output. 1.2 and 1.1+.01 cannot be
represented exactly as floats.
Try java.math.BigDecimal.new(‘1.2’).to_s

On Thu, May 12, 2011 at 11:13 AM, Christian MICHON <

On Thu, May 12, 2011 at 9:17 PM, Rohit N.
[email protected] wrote:

Problem is with the input, not the output. 1.2 and 1.1+.01 cannot be
represented exactly as floats.
Try java.math.BigDecimal.new(‘1.2’).to_s

I moved away from BigDecimal and try this instead using double. I
manage to convert them into binary representation (this was my
original question: I still wish to do the same with BigDecimal)

irb(main):001:0> require ‘java’
true
irb(main):002:0> a = 1.2
1.2
irb(main):003:0> b = 1.1 + 0.1
1.2

irb(main):004:0> java.lang.Double.new(a).to_s
“1.2”
irb(main):005:0> java.lang.Double.new(b).to_s
“1.2000000000000002”

irb(main):006:0>
java.lang.Long.toBinaryString(java.lang.Double.doubleToLongBits(a.to_java.doubleValue))
“11111111110011001100110011001100110011001100110011001100110011”
irb(main):007:0>
java.lang.Long.toBinaryString(java.lang.Double.doubleToLongBits(b.to_java.doubleValue))
“11111111110011001100110011001100110011001100110011001100110100”

irb(main):008:0> a == b
false
irb(main):009:0> b - a
2.22044604925031e-16


Christian

On Fri, 2011-05-13 at 09:20 +0200, Christian MICHON wrote:

On Thu, May 12, 2011 at 9:17 PM, Rohit N.
[email protected] wrote:

Problem is with the input, not the output. 1.2 and 1.1+.01 cannot be
represented exactly as floats.
Try java.math.BigDecimal.new(‘1.2’).to_s

I moved away from BigDecimal and try this instead using double. I
manage to convert them into binary representation (this was my
original question: I still wish to do the same with BigDecimal)

So you want some way of doing BigDecimal.toBinaryString? That’s going
to be tricky, as a bigdecimal is represented using a couple of different
values (depends on implementation, but should be something like sign, a
coefficient and an exponent)


Nick G.
Developer @ Media Service Provider
+44 207 729 4797

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs