Search code examples
javabigdecimal

How to compare two big decimal


I am having following code, however I am not able to understand why the two bigdecimal are not considered as equal

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        BigDecimal b = new BigDecimal(13.90);
        BigDecimal b2 = new BigDecimal("13.9");
        System.out.println(b.compareTo(b2));
    }
}

This code outputs 1 as output. Why would that be the case? Shouldn't it be 0?

Also if I write 13.9 instead of "13.9" it gives 0 as output


Solution

  • Because you are assuming that if you use 13.9 it will exactly be 13.9. Try printing the values of b and b2 and you'll see that the 13.9 is actually 13.9000000000000003552713678800500929355621337890625, and the parsed string value is 13.9. So b is (slightly) higher than b2.

    public static void main(String...strings) {
                BigDecimal b = new BigDecimal(13.9);
                BigDecimal b2 = new BigDecimal("13.9");
                System.out.printf("%s %s %d%n", b, b2, b.compareTo(b2));
    }
    

    Gives as output:

    13.9000000000000003552713678800500929355621337890625 13.9 1
    

    On the topic of floating point mathemetics you might want to read Why Are Floating Point Numbers Inaccurate? and other links available on stackoverflow.