Search code examples
javacomparisonbigintegerbigdecimal

java - compare BigInteger with BigDecimal


I want to compare a BigInteger with a BigDecimal. For example, the integer 10 should be equal to the decimal 10.0.

Why does the following return false? I am creating a new decimal from the integer, and then comparing the two decimals.

System.out.println(new BigDecimal(BigInteger.valueOf(10)).equals(BigDecimal.valueOf(10.0)));

This returns true:

System.out.println(new BigDecimal(BigInteger.valueOf(10)).equals(BigDecimal.valueOf(10)));

How can I correctly compare a BigInteger with a BigDecimal in the mathematical/human definition (10 == 10.0)?


Solution

  • For BigInteger and BigDecimal you should use the compareTo method to check if their value is the same

    System.out.println(new BigDecimal(BigInteger.valueOf(10)).compareTo(BigDecimal.valueOf(10.0)));