Member-only story

Mastering Precision: Solving JavaScript’s Floating-Point Arithmetic Challenges 🧮💻

Xiuer Old
3 min readDec 30, 2024

Introduction

In front-end development, we often encounter requirements for price and amount calculations. These calculations typically demand precision to a specific number of decimal places. However, due to JavaScript’s inherent limitations, strange issues can arise when handling floating-point arithmetic, leading to inaccurate calculations.

This article aims to analyze the causes of this problem by examining its manifestations and summarizing some universal solutions for your reference.

Revisiting the Phenomenon 🔍

Let’s look at some common issues encountered during numerical calculations in JavaScript, professionally known as precision loss:

// Addition
0.1 + 0.2 = 0.30000000000000004
0.7 + 0.1 = 0.7999999999999999

// Subtraction
1.5 - 1.2 = 0.30000000000000004
0.3 - 0.2 = 0.09999999999999998

// Multiplication
19.9 * 100 = 1989.9999999999998
0.7 * 180 = 125.99999999999999

// Division
0.3 / 0.1 = 2.9999999999999996
0.69 / 10 = 0.06899999999999999

Problem Analysis 🔬

JavaScript numbers are 64-bit double-precision floating-point numbers, following the IEEE 754 standard. This standard defines the format of…

--

--

Xiuer Old
Xiuer Old

Written by Xiuer Old

🔥Little brother teaches front-end and AI online🌈

No responses yet