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.
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.