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 |
---|---|
![]() |
![]() |
This Content was originally posted in linkedin View Post