DEV Community

Discussion on: ⛵ Sailing the Choppy Waters of Floating-Point Precision in JavaScript 🔢

Collapse
 
oculus42 profile image
Samuel Rouse

Broader awareness of IEEE 754 limitations can be critical when developing and validating functionality.

One piece that is often overlooked is the limited significant digits that can cause confusion when numbers don't behave as expected. The number of significant digits is fixed and relates to the total amount of detail, not how large or small the number is:

// We can represent very large or small numbers
//  but precision is limited
1.4327194e27         // 1.4327194e+27
1.4327194e27 === (1.4327194e27 + 1)  // true

// Large numbers don't reliably represent decimals
90000000000000.11    // 90000000000000.11
1000000000000000.11  // 1000000000000000.1
2000000000000000.11  // 2000000000000000

// Precision loss doesn't line up with decimal numbers
140737488355327.11   // 140737488355327.11 
140737488355328.11   // 140737488355328.12

// Precision loss can seem inconsistent
14.073748835532711   // 14.073748835532712
14.073748835532811   // 14.073748835532811
Enter fullscreen mode Exit fullscreen mode

Much of the work comes down to understanding the realistic data for your application. If you are processing financial transactions you are unlikely to take an order of one quadrillion dollars less one cent, but if dealing with multiplication you can rapidly exceed the precision limits of the built in number format.

999,999,999,999,999.99   // 1000000000000000

123456.78 * 0.1234567    // 15241.566651426001
Enter fullscreen mode Exit fullscreen mode
Collapse
 
best_codes profile image
Best Codes

Yep. I've been working on a precise feels like calculation that takes data from temperature, humidity, pressure, and wind speed and give me a number — then I discovered that my number was inaccurate because, with this error in JS, and some rather important multiplication and exponents, my number got wacky very quickly.
Thankfully, there are JS libraries like Big.js and math.js to help solve these issues. 😅