我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
这个函数对我有用。你只需输入数字和你想要舍入的位置,它就可以轻松地完成所需的操作。
round(source, n) {
let places = Math.pow(10, n);
return Math.round(source * places) / places;
}
其他回答
我为自己编写了以下一组函数。也许这对你也有帮助。
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
这可能会帮助您:
var result = Math.round(input*100)/100;
有关更多信息,您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性
根据评论中已给出的答案,链接至http://jsfiddle.net/AsRqx/,下面的一个对我来说很好。
function C(num)
{
return +(Math.round(num + "e+2") + "e-2");
}
function N(num, places)
{
return +(Math.round(num + "e+" + places) + "e-" + places);
}
C(1.005);
N(1.005, 0);
N(1.005, 1); // Up to 1 decimal places
N(1.005, 2); // Up to 2 decimal places
N(1.005, 3); // Up to 3 decimal places
这是最简单、更优雅的解决方案(我是世界上最好的;):
function roundToX(num, X) {
return +(Math.round(num + "e+"+X) + "e-"+X);
}
//roundToX(66.66666666,2) => 66.67
//roundToX(10,2) => 10
//roundToX(10.904,2) => 10.9
具有回退值的现代语法替代
const roundToX = (num = 0, X = 20) => +(Math.round(num + `e${X}`) + `e-${X}`)
它可能对你有用,
Math.round(num * 100)/100;
了解toFixed和round之间的区别。您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性。