toFixed 函数无法正常工作(请给出原因而不是替代方案)
toFixed function not working properly ( please give a reason not an alternative)
toFixed()
函数对浮点值的响应不同。
例如:
var a = 2.555;
var b = 5.555;
console.log(a.toFixed(2)); /* output is 2.56 */
console.log(b.toFixed(2)); /* output is 5.55 */
对于 2.555/3.555 结果是 (2.56/3.56)
和
对于其他值(不确定所有值)它显示 #.55(# 指代任何数字)
我很困惑,谁能帮帮我。
提前致谢。
试试这个Demo Here
function roundToTwo(num) {
alert(+(Math.round(num + "e+2") + "e-2"));
}
roundToTwo(2.555);
roundToTwo(5.555);
toFixed() 方法取决于浏览器向下舍入或保留。
这是这个问题的解决方案,检查最后的“5”
var num = 5.555;
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(2);
或者可重复使用的函数就像
function toFixedCustom(num,upto){
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(upto);
return Final;
}
var a = 2.555;
var b = 5.555;
console.log(toFixedCustom(a,2));
console.log(toFixedCustom(b,2));
Javascript 使用数字的二进制浮点表示法 (IEEE754)。
使用此表示法,唯一可以精确表示的数字采用 n/2m 形式,其中 n
和 m
都是整数。
任何非有理数的分母是 2 的整数次方的数都不可能精确表示,因为在二进制中它是一个周期数(它在小数点后有无限的二进制数字)。
数字0.5
(即1/2)很好,(二进制只是0.1₂
)但是例如0.55
(即11/20)不能准确表示(在二进制中它是 0.100011001100110011₂…
即 0.10(0011)₂
最后一部分 0011₂
重复无限次)。
如果您需要进行任何结果取决于精确十进制数的计算,则需要使用精确十进制表示法。如果小数位数是固定的(例如 3),一个简单的解决方案是将所有值乘以 1000 将它们保持为整数...
2.555 --> 2555
5.555 --> 5555
3.7 --> 3700
并在进行乘法和除法时相应地调整您的计算(例如,在将两个数字相乘后,您需要将结果除以 1000)。
IEEE754 双精度格式对于最大 9,007,199,254,740,992 的整数是准确的,这通常足以 prices/values(四舍五入是最常见的问题)。
toFixed()
函数对浮点值的响应不同。
例如:
var a = 2.555;
var b = 5.555;
console.log(a.toFixed(2)); /* output is 2.56 */
console.log(b.toFixed(2)); /* output is 5.55 */
对于 2.555/3.555 结果是 (2.56/3.56)
和
对于其他值(不确定所有值)它显示 #.55(# 指代任何数字)
我很困惑,谁能帮帮我。
提前致谢。
试试这个Demo Here
function roundToTwo(num) {
alert(+(Math.round(num + "e+2") + "e-2"));
}
roundToTwo(2.555);
roundToTwo(5.555);
toFixed() 方法取决于浏览器向下舍入或保留。
这是这个问题的解决方案,检查最后的“5”
var num = 5.555;
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(2);
或者可重复使用的函数就像
function toFixedCustom(num,upto){
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(upto);
return Final;
}
var a = 2.555;
var b = 5.555;
console.log(toFixedCustom(a,2));
console.log(toFixedCustom(b,2));
Javascript 使用数字的二进制浮点表示法 (IEEE754)。
使用此表示法,唯一可以精确表示的数字采用 n/2m 形式,其中 n
和 m
都是整数。
任何非有理数的分母是 2 的整数次方的数都不可能精确表示,因为在二进制中它是一个周期数(它在小数点后有无限的二进制数字)。
数字0.5
(即1/2)很好,(二进制只是0.1₂
)但是例如0.55
(即11/20)不能准确表示(在二进制中它是 0.100011001100110011₂…
即 0.10(0011)₂
最后一部分 0011₂
重复无限次)。
如果您需要进行任何结果取决于精确十进制数的计算,则需要使用精确十进制表示法。如果小数位数是固定的(例如 3),一个简单的解决方案是将所有值乘以 1000 将它们保持为整数...
2.555 --> 2555
5.555 --> 5555
3.7 --> 3700
并在进行乘法和除法时相应地调整您的计算(例如,在将两个数字相乘后,您需要将结果除以 1000)。
IEEE754 双精度格式对于最大 9,007,199,254,740,992 的整数是准确的,这通常足以 prices/values(四舍五入是最常见的问题)。