我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
我只是想根据前面提到的答案分享我的方法:
让我们创建一个函数,将任何给定的数值舍入到给定的小数位数:
function roundWDecimals(n, decimals) {
if (!isNaN(parseFloat(n)) && isFinite(n)) {
if (typeof(decimals) == typeof(undefined)) {
decimals = 0;
}
var decimalPower = Math.pow(10, decimals);
return Math.round(parseFloat(n) * decimalPower) / decimalPower;
}
return NaN;
}
并为数字原型引入一种新的“舍入”方法:
Object.defineProperty(Number.prototype, 'round', {
enumerable: false,
value: function(decimals) {
return roundWDecimals(this, decimals);
}
});
您可以测试它:
函数舍入WDecimals(n,小数){if(!isNaN(parseFloat(n))&&isFinite(n){if(typeof(小数)==typeof(未定义)){小数=0;}var decimalPower=数学.pow(10,小数);return Math.round(parseFloat(n)*decimalPower)/decimalPower;}返回NaN;}Object.defineProperty(Number.prototype,'round'{可枚举:false,值:函数(小数){返回舍入WDecimals(this,小数);}});var舍入=[{num:10,小数:2},{num:1.7777777,小数:2},{num:9.1,小数:2},{num:55.55,小数:1},{num:55.549,小数:1},{num:55,小数:0},{num:54.9,小数:0},{num:-55.55,小数:1},{num:-55.551,小数:1},{num:-55,小数:0},{num:1.005,小数:2},{num:1.005,小数:2},{num:198000000007,小数:2},],table='<table border=“1”><tr><th>Num</th><th>小数</th><th>结果</th></tr>';$.each(roundables,function(){表+='<tr>'+“<td>”+此.num+“</td>”+“<td>”+此小数+“</td>”+'<td>'+this.num.round(this.decimals)+'</td>'+'</tr>';});table+=“</table>”;$('.results').append(表);<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><div class=“results”></div>
其他回答
我知道有很多答案,但大多数答案在某些特定情况下都有副作用。
没有任何副作用的最简单和最短的解决方案如下:
Number((2.3456789).toFixed(2)) // 2.35
它正确舍入并返回数字而不是字符串
console.log(Number((2.345).toFixed(2))) // 2.35
console.log(Number((2.344).toFixed(2))) // 2.34
console.log(Number((2).toFixed(2))) // 2
console.log(Number((-2).toFixed(2))) // -2
console.log(Number((-2.345).toFixed(2))) // -2.35
console.log(Number((2.345678).toFixed(3))) // 2.346
最简单的方法:
+num.to固定(2)
它将其转换为字符串,然后再转换为整数/浮点。
尝试使用jQuery.number插件:
var number = 19.8000000007;
var res = 1 * $.number(number, 2);
在Node.js环境中,我只使用roundTo模块:
const roundTo = require('round-to');
...
roundTo(123.4567, 2);
// 123.46
使用类似的方法“parseFloat(parseFlat(value).toFixed(2))”
parseFloat(parseFloat("1.7777777").toFixed(2))-->1.78
parseFloat(parseFloat("10").toFixed(2))-->10
parseFloat(parseFloat("9.1").toFixed(2))-->9.1