Javascript Number的精度问题

项目中发现使用Number对象的toFixed(2),没有进行四舍五入的操作,如:

var test = 0.6667; 
console.log(Number(test).toFixed(2));// 输出 0.66 ,先将test转变成字符串,结果的小数点后由指定位数的数字

这明显是存在问题的,后来在网上找了些资料,发现可以这样实现小数四舍五入的功能。

//思路:先使用round函数四舍五入成整数,然后再保留指定小数位
Object.prototype.round = function (number,fractionDigits){
    number      = number + 1/Math.pow(10,number.toString().length-1);//往最后补一位
    return Math.round(number*Math.pow(10,fractionDigits)) / Math.pow(10,fractionDigits);
};

console.log(round(test,2));// 输出 0.67


--------------更新修复 ------2014.4.26------------

实际测试发现,本文实现的round函数存在一个重大的问题,就是当number为整数时,得到的值会在原来的基础上+1,如round(0,2)---->得到结果1.00,显然是有问题的。修正后的round函数如下:

//思路:先使用round函数四舍五入成整数,然后再保留指定小数位
Object.prototype.round = function (number,fractionDigits){
    //四舍五入
    number = Math.round(number*Math.pow(10,fractionDigits)) / Math.pow(10,fractionDigits);
    //取小数位
    return Number(number.toFixed(fractionDigits));
};

console.log(round(test,2),round(0,2));// 输出 0.67、0.00


你可能感兴趣的:(JavaScript,number)