Code Smell 71 — Magic Floats Disguised as Decimals
Don’t trust numbers on immature languages like JavaScript.

Problems
- Principle of Least Surprise Violation
- Accidental Complexity
- Wrong decimal representations.
Solutions
1. Choose Mature Languages.
2. Represent Decimals with Decimals.
Sample Code
Wrong
Right
Detection
Since this is a language feature, it is difficult to detect. We can ask our linters to prevent us from manipulating numbers this way.
Tags
- JavaScript
- Premature Optimization
Conclusion
My first programming language was Commodore's basic back in 1985.
I was very surprised to discover that 1+1+1 was not always 3. Then they introduced integer types.
JavaScript is 30 years younger, and it has the same immaturity problems.
Relations
More info
Here is the technical (and accidental) explanation.
Please, don’t argue telling this is fine and expected since this is the binary representation.
These numbers are decimal, we should represent them as decimals.
If you think representing them as floats is a great performance improvement, you are wrong.
Premature optimization is the root of all evil.
List of languages with this defect:
The purpose of computing is insight, not numbers.
Richard Hamming
This article is part of the CodeSmell Series.