How to handle rounding errors in Java's BigDecimal -


i'm working open source project (axil) implements scripting engine inside of java applications , i've hit major stumbling block while trying utilize bigdecimal's rounding. seems bigdecimal converting input scientific notation , applying passed in precision coefficient of sn representation of number, rather non-sn representation. example:

new bigdecimal("-232454.5324").round(new mathcontext(2, roundingmode.half_up)).tostring()

produces result of -2.3e+5. presents 2 problems me. first, expecting result of -232454.5 (-2.324545e+5), getting -230000 throws off math involves result. , second, not expecting, nor can find way around, getting results in sn (though expect there formatting method out there haven't yet stumbled across).

now due nature of project, can make few expectations size/type of numbers getting passed round() method, solution needs highly modular. have suggestions? if helpful here's link google code issue report bug in project. and here link project homepage.

any appreciated.

don't use round method , use setscale instead, argument 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 setscale returns new bigdecimal instance, doesn't change scale of current instance.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -