DEV Community

Cover image for ⛵ Sailing the Choppy Waters of Floating-Point Precision in JavaScript 🔢

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

Best Codes on March 11, 2024

Ahoy there, fellow JavaScript sailors! 🚢 Today, we're setting sail on the treacherous seas of floating-point precision. Grab your life jackets, bec...
Collapse
 
kshyun28 profile image
Jasper Gabriel

As a JavaScript developer, this will always be a recurring caveat that needs proper consideration, especially for applications needing precise calculations.

Have been using a mix of BigNumber and .toFixed() for my needs.

toFixed works well if you only need to handle small decimal places, but for ensuring accuracy for numbers with a lot of decimal places, BigNumber does the job (so far).

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

Collapse
 
rollcode22 profile image
Roll Code

Great post. I thought the sailor theme was fun.

Collapse
 
best_codes profile image
Best Codes

Awesome! I made some edits to improve the readability of the lists as well.