JoeliusCaeser
JoeliusCaeser

Reputation: 85

How to handle rounding errors in Java's BigDecimal

I'm working with open source project (axil) that implements a scripting engine inside of java applications and I've hit a major stumbling block while trying to utilize BigDecimal's rounding. It seems that BigDecimal is converting my input to scientific notation and then applying my passed in precision to the coefficient of the SN representation of the number, rather than to its non-SN representation. For example:

new BigDecimal("-232454.5324").round(new MathContext(2, RoundingMode.HALF_UP)).toString()

produces a result of -2.3E+5. This presents two problems for me. First, I am expecting a result of -232454.5 (-2.324545E+5), so getting -230000 throws off any math that involves the result. And second, I am not expecting, nor can I find a way around, getting the results in SN (though I expect there is a formatting method out there that I haven't yet stumbled across).

Now due to the nature of the project, we can make very few expectations about what size/type of numbers will be getting passed into the round() method, so any solution needs to be highly modular. Does anyone have any suggestions? If it would be helpful here's a link to the google code issue report for this bug in the project. And here is a link to the project homepage.

Any help is very much appreciated.

Upvotes: 3

Views: 6365

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198033

A MathContext takes a precision, which is the total number of significant digits -- before and after the decimal place -- in the result. BigDecimal's logic is correct here.

Upvotes: 1

Bogatyr
Bogatyr

Reputation: 36

I would do it like that:

BigDecimal number = new BigDecimal("22.2222").setScale(0, RoundingMode.UP);

if (number.intValue() % 2 != 0) {
    number = number.add(BigDecimal.ONE);
}

System.out.println(number); // => 24

Upvotes: 1

Kennet
Kennet

Reputation: 5796

Don't use the round method , use setScale instead, where argument is number of decimals:

BigDecimal bd = new BigDecimal("-232454.5324").setScale(1,
                RoundingMode.HALF_UP);
String string = bd.toPlainString();
System.out.println(string); // prints -232454.5

Also note that setScale returns a new BigDecimal instance, it doesn't change the scale of the current instance.

Upvotes: 9

Related Questions