#Javascript Number类型那些你可能不知道的小细节
###你会如何实现一个数字比较的Function
我想所有的js开发者都应该可以想到
function simpleCompaire(num1, num2) {
return num1 === num2
}
这样的代码是可以实现部分数字的比较。注意我说的是部分,也就是说这个函数是有bug的
如果我们这样调用这个函数
simpleCompaire(0.3, 0.1 + 0.2)) // false
打印的结果会是false,为什么会是false呢? 看下面代码
console.log(0.1 + 0.2) // 0.30000000000000004
console.log(0.3) // 0.3
按照我们的想法, 0.1 + 0.1 就应该是0.3。然而我们在js计算的结果却是0.30000000000000004
why? whats wrong with js?
我们都知道,js是一个弱类型的语言,不像java那样,数字类型的有byte、short、int、long、float、double
js语言只实现了浮点数值类型,然而浮点数字类型有一个缺点,那就是机器计算会在某些情况下出现出乎意料的结果
但这并不意味着我们需要认为0.3不等于0.1 + 0.2。 js也给我们提供了解决方案
console.log(Number.EPSILON) // 2.220446049250313e-16
function compareNum(num1, num2) {
return Math.abs(num1 - num2) < Number.EPSILON
}
console.log(compareNum(0.1 + 0.2, 0.3)) //true
js在Number中提供了一个常量,当两个数字的差的绝对值小于这个数的时候,就可以认为这两个数是相等的。
附:
当代码写到这里,就应该是结束了,但是,作为一个与用户体验最近的大前端工程师,这个函数还是可以更好的
function compareNum(num1, num2) {
if (
typeof num1 !== 'Number'
|| typeof num2 !== 'Number'
) {
throw new Error('please enter type Number')
}
return Math.abs(num1 - num2) < Number.EPSILON
}
你以为这就完了? 千万不要忘记我们不是Number 又是Number的小可爱NaN,所以 代码还可以
function compareNum(num1, num2) {
if (typeof num1 !== 'number' || typeof num2 !== 'number') {
throw new Error('please enter type Number')
}
// es6以前Number.isNaN()的Profill
if (!Number.hasOwnProperty(isNaN)) {
// 利用NaN是js中惟一不自等的特性
Number.isNaN = function (num) {
if (typeof num !== 'number'){
throw new Error('please enter type Number')
}
return num !== num
}
}
// 验证没有NaN
if (Number.isNaN(num1) || Number.isNaN((num2))) {
throw new Error('do not enter NaN')
}
return Math.abs(num1 - num2) < Number.EPSILON
}
搞完收工,脱离低级趣味的第一天!