2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-01-27 13:42:22 +01:00
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++``.
2020-06-30 12:48:07 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:07 +02:00
----
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
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:07 +02:00
----
float a = 16777216.0f;
float b = 1.0f;
BigDecimal c = BigDecimal.valueOf(a).add(BigDecimal.valueOf(b));
double d = (double)a + (double)b;
----
2023-05-03 11:06:20 +02:00
=== Exceptions
2020-06-30 12:48:07 +02:00
This rule doesn't raise an issue when the mathematical expression is only used to build a string.
2020-06-30 14:49:38 +02:00
2023-05-25 14:18:12 +02:00
[source,text]
2020-06-30 12:48:07 +02:00
----
System.out.println("["+getName()+"] " +
"\n\tMax time to retrieve connection:"+(max/1000f/1000f)+" ms.");
----
2023-05-03 11:06:20 +02:00
== Resources
2020-06-30 12:48:07 +02:00
2020-12-21 15:38:52 +01:00
* https://wiki.sei.cmu.edu/confluence/x/CtcxBQ[CERT, FLP02-C.] - Avoid using floating-point numbers when precise computation is needed
2020-06-30 12:48:07 +02:00