我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
另一种方法是使用库。使用Lodash:
const _ = require("lodash")
const roundedNumber = _.round(originalNumber, 2)
其他回答
避免舍入到任意位数的二进制问题的适当方法是:
function roundToDigits(number, digits) {
return Number(Math.round(Number(number + 'e' + digits)) + 'e-' + digits);
}
修复toFixed()函数的一种方法是:
Number.prototype.toFixed = (prototype => {
const toFixed = prototype.toFixed;
// noinspection JSVoidFunctionReturnValueUsed
return function (fractionDigits) {
if (!fractionDigits) {
return toFixed.call(this);
} else {
// Avoid binary rounding issues
fractionDigits = Math.floor(fractionDigits);
const n = Number(Math.round(Number(+this + 'e' + fractionDigits)) + 'e-' + fractionDigits);
return toFixed.call(n, fractionDigits);
}
};
})(Number.prototype);
可以使用.toFixed(小数位数)。
var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23
var roundUpto = function(number, upto){
return Number(number.toFixed(upto));
}
roundUpto(0.1464676, 2);
toFixed(2):这里2是我们要舍入的位数。
使用Math.rround():
Math.round(num * 100) / 100
或者更具体地说,为了确保1.005这样的数字正确,请使用Number.EPSILON:
Math.round((num + Number.EPSILON) * 100) / 100
要不处理许多0,请使用以下变体:
Math.round(num * 1e2) / 1e2