
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
45 lines
1.1 KiB
Plaintext
45 lines
1.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
For small numbers, ``++float++`` math has enough precision to yield the expected value, but for larger numbers, it does not. ``++BigDecimal++`` is the best alternative, but if a primitive is required, use a ``++double++``.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,text]
|
|
----
|
|
float a = 16777216.0f;
|
|
float b = 1.0f;
|
|
float c = a + b; // Noncompliant; yields 1.6777216E7 not 1.6777217E7
|
|
|
|
double d = a + b; // Noncompliant; addition is still between 2 floats
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,text]
|
|
----
|
|
float a = 16777216.0f;
|
|
float b = 1.0f;
|
|
BigDecimal c = BigDecimal.valueOf(a).add(BigDecimal.valueOf(b));
|
|
|
|
double d = (double)a + (double)b;
|
|
----
|
|
|
|
|
|
=== Exceptions
|
|
|
|
This rule doesn't raise an issue when the mathematical expression is only used to build a string.
|
|
|
|
[source,text]
|
|
----
|
|
System.out.println("["+getName()+"] " +
|
|
"\n\tMax time to retrieve connection:"+(max/1000f/1000f)+" ms.");
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
* https://wiki.sei.cmu.edu/confluence/x/CtcxBQ[CERT, FLP02-C.] - Avoid using floating-point numbers when precise computation is needed
|
|
|