Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Lost precision when do number format

 
Ralph Ma
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wanna convert a bigdecimal to a formated string. but, after conversion, I found the precision was lost. How can I handle it?
Thanks


eg:
String s="123456789123456789";
BigDecimal bd=new BigDecimal(s);
DecimalFormat df=new DecimalFormat();
System.out.println(df.format(bd));

The expected value is:123,456,789,123,456,789
While the acctal output is:123,456,789,123,456,784
 
Kevin Huang
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that df.format(bd) casts bd into double, and the precision is lost.
 
Ralph Ma
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kevin Huang:
The problem is that df.format(bd) casts bd into double, and the precision is lost.


Would you mind to give me some advices to solve this problem?
Thanks
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What JDK and OS are you trying to run that program?

I ran this in JDK 1.5 under Linux (Ubuntu) and it worked as expected. Even this bigger number,printed just fine:



Prints 123,456,789,123,456,789,123,456,789
 
Kevin Huang
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
replace
System.out.println(df.format(bd));
by
System.out.println(df.format(bd.longValue()));
will get expected string.

I'm suprised that Linux will give different output (since overloading is done at the compile time, not run time). I'm using jdk 1.4 on Windows. Could anyone please try it on Linux using 1.4?
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On JDK 1.4.2_12 under Linux I got rounding problems.

This code:



Produces this output: 123,456,789,123,456,790,000,000,000

One more reason to give the jump and try to tame the Tiger.
 
Campbell Ritchie
Sheriff
Posts: 48445
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does the toString() method supply what you want?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic