aspose file tools*
The moose likes Beginning Java and the fly likes BigDecimal - strange errors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "BigDecimal - strange errors" Watch "BigDecimal - strange errors" New topic
Author

BigDecimal - strange errors

Don Smathers
Ranch Hand

Joined: Mar 04, 2001
Posts: 31
Please look a the following code and its result
import java.math.*;
public class TestEm
{
public static void main ( String [ ] args )
{
System.out.println( new BigDecimal(0.1234567891234567890001).setScale( 20, BigDecimal.ROUND_DOWN ) ) ;
System.exit(0);
}
}
// running the app produces 0.12345678912345678379, the 379 was 90001.
Any ideas on a> why this is happening and
b> how to get BigDecimal to work properly??
Thanks - Don
Carl Trusiak
Sheriff

Joined: Jun 13, 2000
Posts: 3340
The problem is occuring because of double and not BigDecimal. You are using the constructor that takes a double agruement and double is rounding the value before it gets to your Object. Using the constructor that uses a String will correct your problem.


------------------
Hope This Helps
Carl Trusiak, SCJP2
[This message has been edited by Carl Trusiak (edited March 23, 2001).]


I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
Don Smathers
Ranch Hand

Joined: Mar 04, 2001
Posts: 31
Carl - thanks Even on re-reading the 'Dictionary' on class libraries, it took two more readings to catch the subtlety that a REALLY big decimal requires a string input.
In fact, it looks like a string may always be the best way to instantiate a BigDecimal object. Does this make good programming sense / practice ?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: BigDecimal - strange errors