Problem with Double to BigDecimal Conversion

F

Forrest Hump

Can anyone tell me why the code sample below returns a different value for
variable b_OLD ?

The value I get for bd1 is 4.1624999999999996447286321199499070644378662109375.
Why does Java not keep it as 4.1625 ?

----------------

double b_OLD = 4.1625;

java.math.BigDecimal bd1 = new java.math.BigDecimal( b_OLD );

System.out.println("BEFORE ROUNDING: " + bd1);

bd1 = bd1.setScale(0, java.math.BigDecimal.ROUND_CEILING);
System.out.println("AFTER ROUNDING: " + bd1);
 
K

Kent Paul Dolan

Forrest Hump said:
Can anyone tell me why the code sample below returns a different value for
variable b_OLD ?
The value I get for bd1 is 4.1624999999999996447286321199499070644378662109375.
Why does Java not keep it as 4.1625 ?
double b_OLD = 4.1625;

java.math.BigDecimal bd1 = new java.math.BigDecimal( b_OLD );

The usual reason: the number whose decimal representation is "4.1625"
cannot be exactly represented as a "binary number with binary point" in
any finite number of bits (and you only get 52 or so), and so the first
roughly 17 decimal digits of the BigDecimal representation are the best
that the double representation could do in binary when expressed instead
in decimal; what the rest is, I don't know, maybe trash, maybe the
remains of the roundoff back from binary to decimal.

xanthian.
 
D

Dario

Forrest said:
double b_OLD = 4.1625;
java.math.BigDecimal bd1 = new java.math.BigDecimal( b_OLD );
System.out.println("BEFORE ROUNDING: " + bd1);

Try:

java.math.BigDecimal bd1 = new java.math.BigDecimal("4.1625");

I hope this will solve your problem.

- Dario
 
D

Dario

Forrest said:
double b_OLD = 4.1625;
java.math.BigDecimal bd1 = new java.math.BigDecimal( b_OLD );
System.out.println("BEFORE ROUNDING: " + bd1);

Try:

java.math.BigDecimal bd1 = new java.math.BigDecimal("4.1625");

I hope this will solve your problem.

- Dario
 
M

Mark Meyer

Kent Paul Dolan said:
The usual reason: the number whose decimal representation is "4.1625"
cannot be exactly represented as a "binary number with binary point" in
any finite number of bits (and you only get 52 or so), and so the first
roughly 17 decimal digits of the BigDecimal representation are the best
that the double representation could do in binary when expressed instead
in decimal; what the rest is, I don't know, ...

The BigDecimal number representation is the exact decimal
representation of the double's binary approximation of 4.1625.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top