# V6068. Suspicious use of BigDecimal class.

The analyzer has found that the BigDecimal class is being used in a way that may lead to unexpected behavior.

This warning is output in the following cases:

1. When the constructor is called on a floating-point value.

Example of non-compliant code:

    BigDecimal bigDecimal = new BigDecimal(0.6);

The documentation covers some aspects of using the constructor this way.

Without going into much detail, an object created in a way like that will have the value 0.59999999999999997779553950749686919152736663818359375 rather than 0,6. This has to do with the fact that floating-point numbers cannot be represented with perfect precision.

The BigDecimal class, however, is primarily used in high-precision calculations. For example, there is precision-critical software that human lives depend on (such as software for airplanes, rockets, or medical equipment). In such software, error even in the 30th decimal digit can be catastrophic.

To avoid that, use one of the following techniques to create BigDecimal objects:

    BigDecimal bigDecimal1 = BigDecimal.valueOf(0.6);
    BigDecimal bigDecimal2 = new BigDecimal("0.6");

2. When the 'equals' method is called whereas the programmer must have intended 'compareTo'.

It is generally assumed that objects should be compared using the 'equals' methods. And this cannot be argued!

When working with an object of the BigDecimal class, the programmer may view it as simply working with an object that could contain a very big real number. So when calling the 'equals' method, they assume that the values under comparison are equivalent.

In that case, the following code may surprise them:

    BigDecimal bigDecimal1 = BigDecimal.valueOf(0.6);
    BigDecimal bigDecimal2 = BigDecimal.valueOf(0.60);
    ....
    if (bigDecimal1.equals(bigDecimal2)) // false
    {
      // code
    }

The trick is that when using the 'equals' method, it is not only the value itself that participates in the comparison but also the number of its significant decimal digits. This is something that the developer may not expect. To compare values without taking their significant decimal digits into consideration, use the 'compareTo' method:

    BigDecimal bigDecimal1 = BigDecimal.valueOf(0.6);
    BigDecimal bigDecimal2 = BigDecimal.valueOf(0.60);
    ....
    if (bigDecimal1.compareTo(bigDecimal2) == 0) // true
    {
      // code
    }

This diagnostic is classified as:

CERT-NUM10-J