Javascript 的 toFixed 函数中的问题 [英] Issue in toFixed function of Javascript

查看:13
本文介绍了Javascript 的 toFixed 函数中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 toFixed(2) 有一个最大的问题,即如果我写 5.555 那么它会显示 5.55,如果我写 5.565 那么它会显示 5.57.我该怎么办?

I find a biggest problem with toFixed(2) i.e. if i write 5.555 then it will display 5.55 and if I write 5.565 then it will display 5.57. What should I do?

这就是我正在做的.声明一个数组并修复第一个数组的所有值并放入第二个数组.

This is what i am doing. Declaring one array and toFixed all values of first array and put in second array.

var arr1 = [25.205,25.215,25.225,25.235,25.245,25.255,25.265,25.275,25.285,25.295]

var arr2 = []

for(i=0;i<10;i++){ arr2[i]= +arr1[i].toFixed(2) }

结果:

arr1 = [25.205, 25.215, 25.225, 25.235, 25.245, 25.255, 25.265, 25.275, 25.285, 25.295]

arr2 = [25.2, 25.21, 25.23, 25.23, 25.25, 25.25, 25.27, 25.27, 25.29, 25.3]

我是否应该为此使用 Math 对象的 Math.floor() 方法.

should i have to use the Math.floor() method of the Math object for this.

Math.floor(number*100)/100

推荐答案

我已经创建了一个为我完成所有工作的函数..

I have create a function which done all for me..

function toFixed(number, precision) {
    var multiplier = Math.pow(10, precision + 1),
        wholeNumber = Math.floor(number * multiplier);
    return Math.round(wholeNumber / 10) * 10 / multiplier;
}

//Call this function to retrive exect value
toFixed((+adjustmentval), 2);

这篇关于Javascript 的 toFixed 函数中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆