Contents

Precision Errors In Javascript

ย 

Recently I have posted a poll ๐ŸŽ™๐Ÿ“Ÿ in linkedin

๐˜ž๐˜ฉ๐˜ข๐˜ต ๐˜ธ๐˜ช๐˜ญ๐˜ญ ๐˜ฃ๐˜ฆ ๐˜ต๐˜ฉ๐˜ฆ ๐˜ท๐˜ข๐˜ญ๐˜ถ๐˜ฆ ๐˜ฐ๐˜ง ๐˜น ๐˜ช๐˜ฏ ๐˜ต๐˜ฉ๐˜ฆ ๐˜ฃ๐˜ฆ๐˜ญ๐˜ฐ๐˜ธ ๐˜‘๐˜ข๐˜ท๐˜ข๐˜š๐˜ค๐˜ณ๐˜ช๐˜ฑ๐˜ต ๐˜ค๐˜ฐ๐˜ฅ๐˜ฆ๐Ÿ‘จโ€๐Ÿ’ป

๐˜ญ๐˜ฆ๐˜ต ๐˜น=0.1 + 0.2 === 0.3;

Even though mathematically this is true, In JavaScript x will be evaluated as false. Majority(66/120) of the people voted for wrong answer. This may be confusing for most of the people and good thing to be aware of! Here is why!๐Ÿ“ข

๐Ÿ‘‰JavaScript (like many other programming languages) uses binary floating-point arithmetic (IEEE 754 standard), which can cause precision errors when representing certain decimal numbers. For example: 0.1 + 0.2 ๐˜ณ๐˜ฆ๐˜ด๐˜ถ๐˜ญ๐˜ต๐˜ด ๐˜ช๐˜ฏ 0.30000000000000004, ๐˜ฏ๐˜ฐ๐˜ต ๐˜ฆ๐˜น๐˜ข๐˜ค๐˜ต๐˜ญ๐˜บ 0.3.

๐Ÿ‘‰You can handle this in below ways: 1๏ธโƒฃ๐˜Œ๐˜ฑ๐˜ด๐˜ช๐˜ญ๐˜ฐ๐˜ฏ ๐˜Š๐˜ฐ๐˜ฎ๐˜ฑ๐˜ข๐˜ณ๐˜ช๐˜ด๐˜ฐ๐˜ฏ:Compare floating-point numbers in JavaScript, you can use a small threshold value called epsilon:

๐˜”๐˜ข๐˜ต๐˜ฉ.๐˜ข๐˜ฃ๐˜ด(0.1+ 0.2- 0.3) < ๐˜•๐˜ถ๐˜ฎ๐˜ฃ๐˜ฆ๐˜ณ.๐˜Œ๐˜—๐˜š๐˜๐˜“๐˜–๐˜•// ๐˜ต๐˜ณ๐˜ถ๐˜ฆ

โ–ชThis checks if the difference between the two numbers is within a very small range, effectively treating them as equal.

Read more about epsilon here

2๏ธโƒฃ๐˜‹๐˜ฆ๐˜ค๐˜ช๐˜ฎ๐˜ข๐˜ญ ๐˜“๐˜ช๐˜ฃ๐˜ณ๐˜ข๐˜ณ๐˜ช๐˜ฆ๐˜ด: Use libraries like BigDecimal.js or Big.js for exact decimal arithmetic when high precision is needed.

Here you can find more details on Number encoding

Poll In Linkedin Output From Console
Image 2 Image 1

This Content was originally posted in linkedin View Post