aspose file tools*
The moose likes Java in General and the fly likes Lost precision when do number format Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Lost precision when do number format" Watch "Lost precision when do number format" New topic
Author

Lost precision when do number format

Ralph Ma
Greenhorn

Joined: Aug 18, 2005
Posts: 10
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


SCJP 1.2<br />SCWCD 1.3<br />SCBCD 1.3<br />SCDJWS
Kevin Huang
Greenhorn

Joined: Mar 27, 2004
Posts: 13
The problem is that df.format(bd) casts bd into double, and the precision is lost.
Ralph Ma
Greenhorn

Joined: Aug 18, 2005
Posts: 10
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

Joined: Dec 31, 2004
Posts: 961
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

Joined: Mar 27, 2004
Posts: 13
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

Joined: Dec 31, 2004
Posts: 961
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

Joined: Oct 13, 2005
Posts: 39876
    
  28
Does the toString() method supply what you want?
 
 
subject: Lost precision when do number format