Unpredictable 'BigDecimal' constructor call
Reports calls to BigDecimal
constructors that accept a double
value. These constructors produce BigDecimal
that is exactly equal to the supplied double
value. However, because doubles are encoded in the IEEE 754 64-bit double-precision binary floating-point format, the exact value can be unexpected.
For example, new BigDecimal(0.1)
yields a BigDecimal
object. Its value is 0.1000000000000000055511151231257827021181583404541015625
which is the nearest number to 0.1 representable as a double. To get BigDecimal
that stores the same value as written in the source code, use either new BigDecimal("0.1")
or BigDecimal.valueOf(0.1)
.
Example:
After the quick-fix is applied:
Inspection options
Option | Type | Default |
---|---|---|
Ignore constructor calls with variable or method call arguments | Checkbox | true |
Ignore constructor calls with multiple literals (e.g. 0.1 + 0.2) | Checkbox | false |
Inspection Details | |
---|---|
Available in: | IntelliJ IDEA 2023.3, Qodana for JVM 2023.3 |
Plugin: | Java, 233.SNAPSHOT |