This article mainly introduces the toFixed rounding method in Javascript. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
toFixed in javascript uses the banker’s rounding rule.
Banker's rounding: The so-called banker's rounding method is essentially a method of rounding to even and leaving even (also known as rounding to five and leaving even).
To put it simply: consider rounding up to five. If the number after five is not zero, add one. If the number after five is zero, it should be odd or even. If the number before five is even, it should be discarded. If the number before five is odd, it should be rounded by one. But whether toFixed is introduced to solve the problem of lack of precision in floating-point calculations, or whether it uses banker's rounding method, it is all to solve the problem of precision, but it cannot do without the binary floating-point environment, but at least it helps us We found the problem, which gave us a solution.
Number.prototype.toFixed = function(length) { var carry = 0; //存放进位标志 var num,multiple; //num为原浮点数放大multiple倍后的数,multiple为10的length次方 var str = this + ''; //将调用该方法的数字转为字符串 var dot = str.indexOf("."); //找到小数点的位置 if(str.substr(dot+length+1,1)>=5) carry=1; //找到要进行舍入的数的位置,手动判断是否大于等于5,满足条件进位标志置为1 multiple = Math.pow(10,length); //设置浮点数要扩大的倍数 num = Math.floor(this * multiple) + carry; //去掉舍入位后的所有数,然后加上我们的手动进位数 var result = num/multiple + ''; //将进位后的整数再缩小为原浮点数 /* * 处理进位后无小数 */ dot = result.indexOf("."); if(dot < 0){ result += '.'; dot = result.indexOf("."); } /* * 处理多次进位 */ var len = result.length - (dot+1); if(len < length){ for(var i = 0; i < length - len; i++){ result += 0; } } return result; }
The general idea of this method is to first find the rounding bit, determine whether the position is greater than or equal to 5, manually round one bit if the condition is met, and then use the parameter size to round the original float The point is amplified exponentially by the parameter of 10, and then all the digits including the rounding bit are removed using the floor, and whether to carry is determined based on our previous manual carry.
The above is the detailed content of Example of toFixed rounding in Javascript. For more information, please follow other related articles on the PHP Chinese website!