# [JavaScript] Number ###### tags: `JavaScript` ## NaN * NaN 與任何數值運算都是 NaN * NaN 不等於 NaN * 使用 `isNaN()` 判斷是否為 NaN ```javascript= typeof NaN; // "number" NaN + 0; // NaN NaN * Infinity; // NaN NaN == NaN; // false NaN === NaN; // false isNaN(NaN); // true isNaN(1); // false isNaN('1'); // false,要注意隱含的 Number() 轉型 isNaN('a'); // true isNaN('NaN'); // true ``` ## Number.EPSILON `Number.EPSILON` 是 1 和 大於 1 的最小浮點數的差值,也就是 2^-52^,大约是 2.2204460492503130808472633361816E-16。 JavaScript 有浮點數運算不精確的問題,例:`0.1 + 0.2 === 0.3;` 會得到 `false`,因為 `0.1 + 0.2` 的結果是 `0.30000000000000004`,故兩者不相等。這時可以透過比對差值是否小於 `Number.EPSILON`,若為 `true`,則當作兩值相等。 ```javascript= function equal(arg1, arg2) { return Math.abs(arg1 - arg2) < Number.EPSILON; } equal(0.1 + 0.2, 0.3); // true equal(0.000000000000001, 0.000000000000002); // false ``` 但在部份運算上還是會有問題,例: ```javascript= equal(0.0000000000000001, 0.0000000000000002); // true,兩者不相等,卻判斷為相等 equal(1000.1 + 1000.2, 2000.3); // false,兩者相等,卻判斷為不相等 ``` 如果想要非常精確的結果,我覺得還是靠工具比較方便,例:MikeMcl 的 [decimal.js](https://github.com/MikeMcl/decimal.js) ```javascript= const num1 = new Decimal(0.0000000000000001); const num2 = new Decimal(0.0000000000000002); console.log(num1.equals(num2)); // false const result = Decimal.add(1000.1, 1000.2).eq(2000.3); console.log(result); // true ``` --- :::info 建立日期:2021-03-07 更新日期:2024-02-10 :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up