Home > Java > javaTutorial > body text

How to compare BigDecimal values ​​in java

WBOY
Release: 2023-04-18 16:25:03
forward
3299 people have browsed it

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相同
Copy after login

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
     }
    }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!