JavaScript 부동소수점 오차 - 0.1 + 0.2 = 0.30000000000000004

IEEE 754 64비트 부동소수점 표준1. 0.1은 이진법으로 무한 반복(0.0001100110011...)이라 근사치 저장됨.

// 해결책
;(1.1 * 10 + 0.1 * 10) / 10 // 정수 변환
parseFloat((1.1 + 0.1).toFixed(1)) // toFixed
Math.abs(1.1 + 0.1 - 1.2) < Number.EPSILON * 1.2 // 비교 시 (오차 × 크기)
// 정밀 계산: decimal.js, big.js, bignumber.js

Number.EPSILON 은 1 근처에서만 맞는 허용 오차다 — 1.1 + 0.1 - 1.2 는 정확히 EPSILON 이라 < 비교가 false 가 된다.2

JS만의 문제 아님. Python, Java, C++ 등 IEEE 754 사용하는 모든 언어에서 동일.


Footnotes

  1. Number - MDN: “The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#.” ↩

  2. Number.EPSILON - MDN: “Important takeaway: do not simply use Number.EPSILON as a threshold for equality testing. Use a threshold that is appropriate for the magnitude and accuracy of the numbers you are comparing.” ↩

#512