Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

BigDecimal - strange errors

 
Don Smathers
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
Don Smathers
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic