我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
这对正数、负数和大数都适用:
function Round(value) {
const neat = +(Math.abs(value).toPrecision(15));
const rounded = Math.round(neat * 100) / 100;
return rounded * Math.sign(value);
}
//0.244 -> 0.24
//0.245 -> 0.25
//0.246 -> 0.25
//-0.244 -> -0.24
//-0.245 -> -0.25
//-0.246 -> -0.25
其他回答
更简单的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
如果使用的是Lodash库,可以使用Lodash的舍入方法,如下所示。
_.round(number, precision)
例如:
_.round(1.7777777, 2) = 1.78
考虑.toFixed()和.toPrecision():
http://www.javascriptkit.com/javatutors/formatnumber.shtml
我读过所有的答案,类似问题的答案和最“好”的解决方案的复杂性都让我不满意。我不想放一个大的圆函数集,或者一个小的圆函数,但在科学记数法上失败了。所以,我想出了这个函数。这可能会对我的处境有所帮助:
function round(num, dec) {
const [sv, ev] = num.toString().split('e');
return Number(Number(Math.round(parseFloat(sv + 'e' + dec)) + 'e-' + dec) + 'e' + (ev || 0));
}
我没有运行任何性能测试,因为我调用它只是为了更新应用程序的UI。该函数为快速测试提供以下结果:
// 1/3563143 = 2.806510993243886e-7
round(1/3563143, 2) // returns `2.81e-7`
round(1.31645, 4) // returns 1.3165
round(-17.3954, 2) // returns -17.4
这对我来说已经足够了。
我尝试了自己的代码。试试看:
function AmountDispalyFormat(value) {
value = value.toFixed(3);
var amount = value.toString().split('.');
var result = 0;
if (amount.length > 1) {
var secondValue = parseInt(amount[1].toString().slice(0, 2));
if (amount[1].toString().length > 2) {
if (parseInt(amount[1].toString().slice(2, 3)) > 4) {
secondValue++;
if (secondValue == 100) {
amount[0] = parseInt(amount[0]) + 1;
secondValue = 0;
}
}
}
if (secondValue.toString().length == 1) {
secondValue = "0" + secondValue;
}
result = parseFloat(amount[0] + "." + secondValue);
} else {
result = parseFloat(amount);
}
return result;
}