Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
int i = 1;
String s = Double.valueOf (i / 1000.0).toString(); // s contains 0.0010
if(s.equals("0.001")) { // Fails
  // Do something
}

Noncompliant Code Example

This noncompliant code example attempts to use a regular expression to eliminate the trailing zeros. However, even though this works for 1/1000.0, for 1/10000.0, it produces the string 1.0E-4. Subsequent comparison operations can still fail.

Code Block
bgColor#FFCCCC

int i = 1;
String s = Double.valueOf (i / 10000.0).toString(); // s contains 0.0010
s = s.replaceFirst("[.0]*$", "");
// ...

Compliant Solution

This compliant solution uses the BigDecimal class and strips the trailing zeros so that future operations do not fail.

...