我想最多四舍五入两位小数,但只有在必要时。
输入:
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;}
其他回答
以下是最简短完整的答案:
function round(num, decimals) {
var n = Math.pow(10, decimals);
return Math.round( (n * num).toFixed(decimals) ) / n;
};
这还考虑了示例情况1.005,它将返回1.01。
一个简单的解决方案是,如果你想四舍五入,可以使用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
从现有的答案中,我找到了另一个似乎很有效的解决方案,它也可以发送字符串,并消除尾随零。
function roundToDecimal(string, decimals) {
return parseFloat(parseFloat(string).toFixed(decimals));
}
如果你派一些公牛来,那就不算什么了。。就像“阿帕”一样。或者它可能会抛出一个错误,我认为这是正确的方法。无论如何,隐藏应该修复的错误(通过调用函数)是不好的。
具有可读选项的函数更直观:
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
一个助手函数,其中rounding是默认舍入:
let rounding = 4;
let round = (number) => { let multiply = Math.pow(10,rounding); return Math.round(number*multiply)/multiply};
console.log(round(0.040579431));
=> 0.0406