Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Literal decimal floating-point numbers can not cannot always be represented precisely using the double primitive type, because the underlying representation of double is binary. This imprecision becomes apparent when a BigDecimal is constructed from a double. precisely represented as an IEEE 754 floating-point value. Consequently, the BigDecimal(double val) constructor must not be invoked with passed a floating-point literalsliteral as an argument when doing so results in an unacceptable loss of precision.

Noncompliant Code Example

This noncompliant code example passes a double value to the BigDecimal constructor. Because the decimal literal 0.1 can not cannot be precisely represented by a double, precision of the BigDecimal is affected.

Code Block
bgColor#FFcccc

// printsPrints 0.1000000000000000055511151231257827021181583404541015625
// when run in FP-strict mode 
System.out.println(new BigDecimal(0.1)); 

Compliant Solution

This compliant solution passes the decimal literal as a String so that the BigDecimal(String val) constructor is invoked , and the precision is preserved.:

Code Block
bgColor#ccccff

// printsPrints 0.1
// when run in FP-strict mode 
System.out.println(new BigDecimal("0.1"));

Risk Assessment

Using the BigDecimal(double val) constructor with decimal floating-point literals can lead to loss of precision.

Guideline

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

NUM13

NUM10-J

low

Low

probable

Probable

low

Low

P6

L2

Automated Detection

Automated detection appears to be is straightforward.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Bibliography

[JLS 2005]

...

ToolVersionCheckerDescription
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.NUM10.BBDCCDo not pass floating point values to the 'BigDecimal' constructor
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V6068
SonarQube
Include Page
SonarQube_V
SonarQube_V
S2111"BigDecimal(double)" should not be used

Bibliography


...

Image Added Image Added Image Added use floating-point variables as loop counters      03. Numeric Types and Operations (NUM)      NUM14-J. Do not rely on the default string representation of floating point values