import java.math.BigDecimal; import java.math.MathContext; public class BigDecimalTest { public static void main(String[] args) { System.out.println(new BigDecimal(0).equals(BigDecimal.ZERO)); System.out.println(new BigDecimal("0").equals(BigDecimal.ZERO)); System.out.println(new BigDecimal(0.0d).equals(BigDecimal.ZERO)); System.out.println(new BigDecimal(0.0f).equals(BigDecimal.ZERO)); //WTF System.out.println(new BigDecimal("0.0").equals(BigDecimal.ZERO)); // false!!! System.out.println(new BigDecimal("0.0").equals(new BigDecimal("0"))); // false!!! System.out.println(new BigDecimal("0.0").equals(new BigDecimal(0.0))); // false!!! //same is with "1" and "1.0", and so on //That's not a precision problem MathContext mc = new MathContext(2); System.out.println(new BigDecimal("0.0", mc).equals(new BigDecimal(0.0, mc))); // false!!! //So, the proper way to compare two big decimals is: System.out.println(new BigDecimal("0.0").compareTo(BigDecimal.ZERO) == 0); }The answer lies in API docs: BigDecimal#equals.
Monday, 18 January 2010
Proper way to compare java.math.BigDecimal
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment