integrated-application-development / integrated-application-development/sonar-delphi

New rule: Floating point numbers should not be compared directly

Open
#71 1 comment 2 reactions 0 assignees View on GitHub
feature rule
Dominant language
Java
Stars
159
Forks
31
Avg merge
5d 4h
Merged PRs (30d)
4

Description

### 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...`:

```delphi
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;
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.