cover-img

Code Smell 71 - Magic Floats Disguised as Decimals

19 May, 2023

0

0

0

TL;DR: Don't trust numbers on immature languages like JavaScript.

Problems

Solutions

  1. Choose Mature Languages.
  2. Represent Decimals with Decimals.

Sample Code

Wrong

console.log(0.2 + 0.1)
// 0.30000000000000004

// We are adding two decimal numbers
// 2/10 + 1/10
// Result should be 3/10 as we learned at school

Right

class Decimal {
constructor(numerator) {
this.numerator = numerator;
}
plus(anotherDecimal) {
return new Decimal(this.numerator + anotherDecimal.numerator);
}
toString() {
return "0." + this.numerator;
}}

console.log((new Decimal(2).plus(new Decimal(1))).toString());
// 0.3

// We can represent the numbers with a Decimal class (storing only the numerator)
// or with a generic Fraction class (storing both the numerator and denominator)

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 64'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

Code Smell 69 - Big Bang (JavaScript Ridiculous Castings)

More Info

Here is the technical (and accidental) explanation.

Technical 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.

Floating Point Standard - 83 pages

Credits

Photo by Stephen Radford on Unsplash


The purpose of computing is insight, not numbers.

Richard Hamming


Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code

0

0

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.