我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
一个简单的解决方案是,如果你想四舍五入,可以使用Lodash的ceil函数。。。
_.round(6.001, 2)
给出6
_.ceil(6.001, 2);
给出6.01
_.ceil(37.4929, 2);
给出37.5
_.round(37.4929, 2);
给出37.49
其他回答
对我来说,Math.rround()没有给出正确的答案。我发现Fixed(2)效果更好。以下是两者的示例:
console.log(数学舍入(43000/80000)*100);//错误的答案console.log(((43000/80000)*100).toFixed(2));//正确回答
如果您不想舍入,请使用以下函数。
function ConvertToDecimal(num) {
num = num.toString(); // If it's not already a String
num = num.slice(0, (num.indexOf(".")) + 3); // With 3 exposing the hundredths place
alert('M : ' + Number(num)); // If you need it back as a Number
}
我在MDN上找到了这个。他们的方法避免了前面提到的1.005的问题。
函数roundToTwo(num){return+(数学舍入(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));
有两种方法可以做到这一点。对于像我这样的人,Lodash的变体
function round(number, precision) {
var pair = (number + 'e').split('e')
var value = Math.round(pair[0] + 'e' + (+pair[1] + precision))
pair = (value + 'e').split('e')
return +(pair[0] + 'e' + (+pair[1] - precision))
}
用法:
round(0.015, 2) // 0.02
round(1.005, 2) // 1.01
如果您的项目使用jQuery或Lodash,您也可以在库中找到适当的舍入方法。
更简单的ES6方法是
const round = (x, n) =>
Number(parseFloat(Math.round(x * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n));
此模式还返回要求的精度。
ex:
round(44.7826456, 4) // yields 44.7826
round(78.12, 4) // yields 78.12