我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
为了记录在案,如果要舍入的数字和位数足够大,缩放方法理论上可以返回无穷大。在JavaScript中,这应该不是问题,因为最大数字是1.7976931348623157e+308,但如果您使用的是非常大的数字或很多小数位数,您可以尝试使用此函数:
Number.prototype.roundTo=函数(数字){var str=this.toString();var split=this.toString().split('e');var scientific=split.length>1;var指数;if(科学){str=拆分[0];var decimal=str.split('.');如果(小数长度<2)返回此;index=十进制[0]。长度+1+位;}其他的index=Math.floor(this).toString().length+1+位数;if(str.length<=索引)返回此;var数字=str[index+1];var num=Number.parseFloat(str.substring(0,索引));如果(数字>=5){var extra=数学.pow(10,-位);返回此<0?num-额外:num+额外;}if(科学)num+=“e”+拆分[1];返回num;}
其他回答
parseFloat(“1.555”).toFixed(2);//返回1.55而不是1.56。
1.55是绝对正确的结果,因为在计算机中不存在1.555的精确表示。如果读数为1.555,则四舍五入至最接近的值=1.55499999999999994(64位浮点)。将这个数字四舍五入到Fixed(2)得到1.55。
如果输入为1.55499999999999,则此处提供的所有其他功能都会给出故障结果。
解决方案:在扫描前加上数字“5”,将数字舍入(更准确地说,从0开始舍入)。仅当数字真的是浮点(有小数点)时才执行此操作。
parseFloat("1.555"+"5").toFixed(2); // Returns 1.56
我发现这适用于我的所有用例:
const round = (value, decimalPlaces = 0) => {
const multiplier = Math.pow(10, decimalPlaces);
return Math.round(value * multiplier + Number.EPSILON) / multiplier;
};
记住这是ES6。ES5的等效版本很容易编写,所以我不打算添加它。
对这个答案稍作修改,似乎效果不错。
作用
function roundToStep(value, stepParam) {
var step = stepParam || 1.0;
var inv = 1.0 / step;
return Math.round(value * inv) / inv;
}
用法
roundToStep(2.55) = 3
roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55
避免舍入到任意位数的二进制问题的适当方法是:
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);
具有可读选项的函数更直观:
function round_number(options) {
const places = 10**options.decimal_places;
const res = Math.round(options.number * places)/places;
return(res)
}
用法:
round_number({
number : 0.5555555555555556,
decimal_places : 3
})
0.556