sonar-delphi icon indicating copy to clipboard operation
sonar-delphi copied to clipboard

New rule: Floating point numbers should not be compared directly

Open fourls opened this issue 2 years ago • 1 comments

Prerequisites

  • [x] This rule has not already been suggested.
  • [x] This should be a new rule, not an improvement to an existing rule.
  • [x] This rule would be generally useful, not specific to my code or setup.

Suggested rule title

Floating point numbers should not be compared directly

Rule description

This rule would identify instances of a floating point value being checked for equality with = or <>.

Rationale

Two floating point numbers may appear to have the same value, but be slightly different due to rounding errors in calculation. This is unpredictable and leads to buggy code.

The following code would print They are not the same...:

A := (0.3 * 3) + 0.1;
B := 1.0;

if A = B then begin
  WriteLn('They are the same!');
end
else begin
  WriteLn('They are not the same...');
end;

fourls avatar Oct 31 '23 03:10 fourls

Good suggestion. this seems like a worthwhile addition.

We should have an exclusion for comparing against 0.

cirras avatar Nov 14 '23 04:11 cirras