Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to compare the value of BigDecimal in java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report