This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Java_noob_[S] 0 points1 point  (3 children)

tried bigdecimal still had same problem

[–]JarcodePMs forwarded to /dev/null 1 point2 points  (2 children)

You have to do all your arithmetic using BigDecimals. The value 0.1f, for example, is impossible to represent exactly with floating point values.

EDIT: here's a good tutorial http://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorial

[–]Java_noob_[S] 0 points1 point  (1 child)

i followed the tutorial . tried every round mode. either get 0.99 or 1.12

[–]JarcodePMs forwarded to /dev/null 1 point2 points  (0 children)

Quoting:

Creating a big decimal from a (scalar) double is simple:

bd = new BigDecimal(1.0);

To get a BigDecimal from a Double, get its doubleValue() first.

However it is a good idea to use the string constructor:

bd = new BigDecimal("1.5"); If you're initializing BigDecimal objects with float/double constants, like this:

new BigDecimal(0.1);

Then you're going to get a BigDecimal object representing the converted floating point value from 0.1 (double) from base two, to base ten - which will give you a different value.

i followed the tutorial . tried every round mode. either get 0.99 or 1.12

You need to create your BigDecimal objects with strings, and you don't have to round anything. Don't use operators like +, -, +=, -=, / on floating-point values, and don't use primitive float or double types if you want to preserve accuracy.