Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

Code Smell 71 — Magic Floats Disguised as Decimals

Maximiliano Contieri
Dev Genius
Published in
2 min readMay 24, 2021

Photo by Stephen Radford on Unsplash

Problems

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:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by Maximiliano Contieri

I’m a senior software engineer specialized in declarative designs. S.O.L.I.D. and agile methodologies fan. Maximilianocontieri.com

No responses yet

Write a response