Home  >  Article  >  Java  >  How to compare BigDecimal values ​​in java

How to compare BigDecimal values ​​in java

WBOY
WBOYforward
2023-04-18 16:25:033285browse

1. Using the equals() method not only requires the values ​​of the two BigDecimals to be equal, but also requires their scale() to be equal.

   BigDecimal d1 = new BigDecimal("123.45");
   BigDecimal d2 = new BigDecimal("123.45000");
   System.out.println(d1.equals(d2)); // false,因为scale不同
   System.out.println(d1.equals(d2.stripTrailingZeros())); // true,因为d2去除尾部0后scale变为2,与d1相同

2. Use the compareTo() method to compare the size of two numbers. It returns -1, 1 and 0 respectively according to the size of the two values, indicating less than, greater than and equal to respectively.

    import java.math.BigDecimal;
    public class Demo {
     public static void main(String[] args) {
      BigDecimal d1 = new BigDecimal("123.45");
      BigDecimal d2 = new BigDecimal("123.45000");
      BigDecimal d3 = new BigDecimal("123.40");
      System.out.println(d1.compareTo(d2)); // 0
      System.out.println(d1.compareTo(d3));//  1
      System.out.println(d3.compareTo(d2));// -1
     }
    }

The above is the detailed content of How to compare BigDecimal values ​​in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete