Number EPSILON Compares Floats Safely
Compare floats with a relative Number.EPSILON tolerance instead of ===, since binary rounding makes 0.1 + 0.2 differ from 0.3 by one resolution step.
Code
// 浮点误差:0.1 + 0.2 !== 0.3,安全比较要用容差而不是 ===
const sum = 0.1 + 0.2;
console.log('sum :', sum);
console.log('naive ===:', sum === 0.3);
// 相对容差:误差预算随数值大小按比例放大,EPSILON 是最小分辨率
function nearlyEqual(a, b, epsilon = Number.EPSILON) {
return Math.abs(a - b) <= epsilon * Math.max(Math.abs(a), Math.abs(b), 1);
}
console.log('epsilon :', nearlyEqual(sum, 0.3));
console.log('distinct :', nearlyEqual(1.5, 1.6));
// 内建数值守卫:整数判断与安全整数范围
console.log('isInteger:', Number.isInteger(42), Number.isInteger(42.5));
console.log('safe :', Number.isSafeInteger(2 ** 53), Number.MAX_SAFE_INTEGER);Output
Captured from a sandboxed run of this snippet in the build pipeline.
sum : 0.30000000000000004
naive ===: false
epsilon : true
distinct : false
isInteger: true false
safe : false 9007199254740991What the code does
Number EPSILON Compares Floats Safely is built around the function nearlyEqual.
Applying it
The primary signature is function nearlyEqual(a, b, epsilon = Number.EPSILON)
The demo output is labeled (sum :, naive ===:, epsilon :), so every printed line maps back to its originating operation.
Statements that matter
return Math.abs(a - b) <= epsilon * Math.max(Math.abs(a), Math.abs(b), 1);
Interactive Tools for This Topic
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `nearlyEqual` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.