How to compare BigDecimal values in java
Apr 18, 2023 pm 04:25 PM
java
bigdecimal
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!
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

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot tools Tags

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Break or return from Java 8 stream forEach?
