How to compare the value of BigDecimal in java
Today, I would like to share with you how to compare the value of BigDecimal in java, the content is detailed, the logic is clear, I believe most people still know too much about this knowledge, so share this article for your reference, hope you can get something after reading this article, let's take a look at it.
1. Using the equals () method requires not only that the values of two BigDecimal are equal, but also that their scale () is equal.
BigDecimal D1 = new BigDecimal ("123.45"); BigDecimal D2 = new BigDecimal ("123.45000"); System.out.println (d1.equals (D2)); / / false, because scale is different from System.out.println (d1.equals (d2.stripTrailingZeros (); / / true, because scale becomes 2 after removing tail 0 on d2, which is the same as D1.
2. Use the compareTo () method to compare the size of two numbers, which returns-1, 1, and 0 according to the size of the two values, representing 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}} above is all the content of the article "how to compare the value of BigDecimal in java". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.