GitHub
CERT Secure Coding

NUM10-J. Do not construct BigDecimal objects from floating-point literals

Literal decimal floating-point numbers cannot always be precisely represented as an IEEE 754 floating-point value. Consequently, the BigDecimal(double val) constructor must not be passed a floating-point literal 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 cannot be precisely represented by a double , precision of the BigDecimal is affected.

Non-compliant code
// Prints 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:

Compliant code
// Prints 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.

Rule Severity Likelihood Detectable Repairable Priority Level
NUM10-J Low Probable Yes Yes P6 L2

Automated Detection

Automated detection is straightforward.

ToolVersionCheckerDescription
Klocwork

2025.2

JAVA.BIGDEC.FLOAT
Parasoft Jtest
2025.2
CERT.NUM10.BBDCCDo not pass floating point values to the 'BigDecimal' constructor
PVS-Studio

7.42

V6068
SonarQube
9.9
S2111"BigDecimal(double)" should not be used

Bibliography

[ JLS 2015 ]


[ Seacord 2015 ]