我想最多四舍五入到小数点后两位,但前提是有必要。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在 JavaScript 中执行此操作?
网友回答:
如果值为文本类型:
parseFloat("123.456").toFixed(2);
如果值为数字:
var numb = 123.23454;
numb = numb.toFixed(2);
有一个缺点,像 1.5 这样的值会给出“1.50”作为输出。@minitech建议的修复:
var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.
这似乎是一个更好的解决方案。但事实并非如此!在某些情况下,它不会正确舍入:Math.round
Math.round(1.005 * 100)/100 // Returns 1 instead of expected 1.01!
toFixed() 在某些情况下也无法正确舍入(在 Chrome v.55.0.2883.87 中测试)!
例子:
parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.
1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.
我想,这是因为 1.555 实际上是幕后的浮点数 1.55499994。
解决方案 1 是使用具有所需舍入算法的脚本,例如:
function roundNumber(num, scale) {
if(!("" + num).includes("e")) {
return +(Math.round(num + "e+" + scale) + "e-" + scale);
} else {
var arr = ("" + num).split("e");
var sig = ""
if(+arr[1] + scale > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
}
}
它也在普伦克。
注意:这不是适合所有人的通用解决方案。有几种不同的舍入算法。您的实现可以不同,这取决于您的要求。另请参阅舍入。
解决方案 2 是避免前端计算并从后端服务器拉取舍入值。
另一种可能的解决方案,也不是防弹的。
Math.round((num + Number.EPSILON) * 100) / 100
在某些情况下,当您对数字(如 1.3549999999999998)进行舍入时,它将返回不正确的结果。它应该是 1.35,但结果是 1.36。
网友回答:
用:Math.round()
Math.round(num * 100) / 100
或者更具体地说,并确保像 1.005 舍入这样的东西正确,请使用 Number.EPSILON :
Math.round((num + Number.EPSILON) * 100) / 100
网友回答:
我在MDN上找到了这个。他们的方式避免了提到的 1.005 问题。
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
console.log('1.005 => ', roundToTwo(1.005));
console.log('10 => ', roundToTwo(10));
console.log('1.7777777 => ', roundToTwo(1.7777777));
console.log('9.1 => ', roundToTwo(9.1));
console.log('1234.5678 => ', roundToTwo(1234.5678));
模板简介:该模板名称为【如何舍入到最多 2 位小数(如有必要)】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。