Decimal numbers cannot be precisely represented as a BigDecimal
if the BigDecimal(double val)
constructor is used.
Noncompliant Code Example
This noncompliant code example passes a double
value to the BigDecimal
constructor. Because of this, precision of the literal is affected.
Code Block | ||
---|---|---|
| ||
// prints 0.1000000000000000055511151231257827021181583404541015625 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.
Code Block | ||
---|---|---|
| ||
// prints 0.1 System.out.println(new BigDecimal("0.1")); |
Risk Assessment
Using the BigDecimal
constructor that accepts decimal literals can lead to loss of precision.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FLP33- J | low | probable | low | P6 | L2 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[JLS 05]
...
FLP03-J. Range check before casting floating point numbers to narrower types 07. Floating Point (FLP) 08. Object Orientation (OBJ)