Issue in toFixed function of Javascript

空扰寡人 提交于 2021-02-08 04:27:41

问题


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) }

Results:

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]

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

Math.floor(number*100)/100

回答1:


This is due to the binary representations of the fractions being slightly more or less than the numbers entered. See the accepted answer HERE for an alternative method of rounding to 2 significant figures.




回答2:


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);


来源:https://stackoverflow.com/questions/29006729/issue-in-tofixed-function-of-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!