So, BigDecimal type is widely used in one of our projects. Here are some interesting facts that I've faced while working with them:
1) According to javadoc, constructor that ussed a Number (new BigDecimal(42.52)) won't give you a predictable value of 42.52. Actual value will have about 30 digits.
"it cannot be represented exactly as a double or, for that matter, as a binary fraction of any finite length" <- javadoc
2) Constructor that uses String (new BigDecimal("42.52")) creates exact value. You definately want this behavior when you create a BigDecimal using a hard coded value (For example, in tests).
3) If you want to compare two BigDecimals, don't use things like bigDecimal.intValue() <= 0. "the low-order 32 bits are returned". Which means that it can not only loose precision, but even return a value with opposite sign.
bigDecimal.doubleValue() saves sign, but not precesion.
Comments (5)
Apr 21, 2008
Timur Strekalov says:
Fun enoughFun enough
Apr 21, 2008
Heiti Allak says:
whats the best thing to do instead of 3whats the best thing to do instead of 3
Apr 21, 2008
Andrei Tkatšov says:
Is it bigDecimal.compareTo() ? http://java.sun.com/j2se/1.4.2/docs/api/java/ma...Is it bigDecimal.compareTo() ?
http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigDecimal.html#compareTo(java.math.BigDecimal)
___
About negative value case:
From: The IEEE standard for floating point arithmetic
_ http://www.psc.edu/general/software/packages/ieee/ieee.html _
Double precision
[S] [EEEEEEEEEEE] [FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF]
[0] [1 11] [12 63]
Apr 21, 2008
Aleksandr Zuikov says:
Jep, compareTo seems to workJep, compareTo seems to work
Apr 21, 2008
Aleksandr Zuikov says:
seems that there was a typo, doubleValue() saves sign, intValue() does not.seems that there was a typo, doubleValue() saves sign, intValue() does not.