我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
MarkG的答案是正确的。这里是任何小数位数的通用扩展。
Number.prototype.round = function(places) {
return +(Math.round(this + "e+" + places) + "e-" + places);
}
用法:
var n = 1.7777;
n.round(2); // 1.78
单元测试:
it.only('should round floats to 2 places', function() {
var cases = [
{ n: 10, e: 10, p:2 },
{ n: 1.7777, e: 1.78, p:2 },
{ n: 1.005, e: 1.01, p:2 },
{ n: 1.005, e: 1, p:0 },
{ n: 1.77777, e: 1.8, p:1 }
]
cases.forEach(function(testCase) {
var r = testCase.n.round(testCase.p);
assert.equal(r, testCase.e, 'didn\'t get right number');
});
})
其他回答
一个简单的解决方案是,如果你想四舍五入,可以使用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
var roundUpto = function(number, upto){
return Number(number.toFixed(upto));
}
roundUpto(0.1464676, 2);
toFixed(2):这里2是我们要舍入的位数。
我为自己编写了以下一组函数。也许这对你也有帮助。
function float_exponent(number) {
exponent = 1;
while (number < 1.0) {
exponent += 1
number *= 10
}
return exponent;
}
function format_float(number, extra_precision) {
precision = float_exponent(number) + (extra_precision || 0)
return number.toFixed(precision).split(/\.?0+$/)[0]
}
用法:
format_float(1.01); // 1
format_float(1.06); // 1.1
format_float(0.126); // 0.13
format_float(0.000189); // 0.00019
对于您的情况:
format_float(10, 1); // 10
format_float(9.1, 1); // 9.1
format_float(1.77777, 1); // 1.78
考虑.toFixed()和.toPrecision():
http://www.javascriptkit.com/javatutors/formatnumber.shtml
这里找到的答案都不正确。臭柴塞曼要求四舍五入,但你们都四舍五进。
要进行汇总,请使用以下命令:
Math.ceil(num * 100)/100;