Decimal numbers cannot be precisely represented as a BigDecimal when the BigDecimal(double val) constructor is used. The primitive type double cannot precisely represent all decimal fractions because its underlying representation is binary. Consequently, the input to the BigDecimal(double val) constructor can lose precision before the constructor is ever invoked.
This noncompliant code example passes a double value to the BigDecimal constructor. Because of this, precision of the literal is affected.
// prints 0.1000000000000000055511151231257827021181583404541015625 System.out.println(new BigDecimal(0.1)); |
This compliant solution passes the decimal literal as a String so that the BigDecimal(String val) constructor is invoked.
// prints 0.1
System.out.println(new BigDecimal("0.1"));
|
Using the BigDecimal(double val) constructor with decimal floating point literals leads to loss of precision.
Guideline |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
FLP08-J |
low |
probable |
low |
P6 |
L2 |
Automated detection appears to be straightforward.
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
[JLS 2005]
FLP07-J. Do not use floating point variables as loop counters Floating Point (FLP) FLP09-J. Do not rely on the default string representation of floating point values