org.sonar.l10n.java.rules.squid.S2164.html Maven / Gradle / Ivy
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
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
float a = 16777216.0f;
float b = 1.0f;
BigDecimal c = BigDecimal.valueOf(a).add(BigDecimal.valueOf(b));
double d = (double)a + (double)b;
© 2015 - 2025 Weber Informatics LLC | Privacy Policy