Search code examples
javabigdecimal

Difference in BigDecimal behavior


I have two pieces of code new BigDecimal("1.240472701") and new BigDecimal(1.240472701). Now if i use compareTo method of java on both the methods then i get that they are not equal.

When i printed the values using System.out.println() method of java. I get different results for both the values. For example

new BigDecimal("1.240472701") -> 1.240472701

new BigDecimal(1.240472701) -> 1.2404727010000000664291519569815136492252349853515625

So i want to understand what could be reason for this?


Solution

  • Since user thegauravmahawar provided the answer from docs. Yes, it is because of Scaling in BigDecimal case.
    So the values might seem equal to You but internally java uses Scaling while storing the value of BigDecimal type.
    Reason: Scaling.

    Improvement:

    You could call setScale to the same thing on the numbers you're comparing: like this

    new BigDecimal ("7.773").setScale(2).equals(new BigDecimal("7.774").setScale (2))
    

    This will save you from making any mistake.