Daily development blog notes

  1. It is forbidden to use BigDecimal's equals method for equal value comparison
     

    BigDecimal, I believe it is familiar to many people, and many people know its usage. This is a type provided in the java.math package that can be used for precise calculations.

    Many people know that in scenarios such as amount expression and amount calculation, double, float and other types cannot be used, but BigDecimal with better accuracy support should be used.

    Therefore, in many payment, e-commerce, financial and other businesses, BigDecimal is used very frequently. And I have to say that this is a very easy to use class, it has many internal methods, such as addition, subtraction, multiplication, division and other operations can be directly called.

    In addition to the need to use BigDecimal to represent numbers and perform digital operations, codes often need to be equal to numbers.

    About this knowledge point, it is also explained in the latest version of "Alibaba Java Development Manual":

 When using BigDecimal's equals method to compare 1 and 1.0, sometimes it is true (when using int, double to define BigDecimal), sometimes it is false (when using String to define BigDecimal)
 

The equals method is not the same as compareTo. The equals method compares two parts, namely value and scale.

BigDecimal is a very useful class that represents high-precision numbers, which provides a lot of rich methods.

However, he needs to be cautious when using his equals method, because when he compares, he not only compares the values ​​of two numbers, but also compares their accuracy. As long as one of the two factors is not equal, the result is also false. ,

If the reader wants to compare the values ​​of two BigDecimals, they can use the compareTo method.

 

Guess you like

Origin blog.csdn.net/weixin_40611659/article/details/108726808