我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
我读过所有的答案,类似问题的答案和最“好”的解决方案的复杂性都让我不满意。我不想放一个大的圆函数集,或者一个小的圆函数,但在科学记数法上失败了。所以,我想出了这个函数。这可能会对我的处境有所帮助:
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
这对我来说已经足够了。
其他回答
2017只需使用本机代码.toFixed()
number = 1.2345;
number.toFixed(2) // "1.23"
如果您需要严格要求并在需要时添加数字,可以使用替换
number = 1; // "1"
number.toFixed(5).replace(/\.?0*$/g,'');
将类型保留为整数,以便以后进行排序或其他算术运算:
Math.round(1.7777777 * 100)/100
1.78
// Round up!
Math.ceil(1.7777777 * 100)/100
1.78
// Round down!
Math.floor(1.7777777 * 100)/100
1.77
或转换为字符串:
(1.7777777).toFixed(2)
"1.77"
请参阅AmrAli的答案,以了解此解决方案的所有不同调整的更全面的运行和性能细分。
var DecimalPrecision=(函数){if(数字.EPSILON===未定义){Number.EPSILON=数学功率(2,-52);}if(Number.isInteger==未定义){Number.isInteger=函数(值){返回值类型==“number”&&isFinite(值)&&数学下限(值)==值;};}this.isRound=函数(n,p){设l=n.toString().split('.')[1].length;返回(p>=l);}this.round=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;如果(n<0)o*=-1;返回数学舍入((n+r)*o)/o;}this.ceil=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回Math.ceil((n+r)*o)/o;}this.flor=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回数学楼层((n+r)*o)/o;}返回此;})();console.log(DecimalPrecision.round(1.005));console.log(DecimalPrecision.ceil(1.005));console.log(DecimalPrecision.floor(1.005));console.log(DecimalPrecision.round(1.0049999));console.log(DecimalPrecision.ceil(1.0049999));console.log(DecimalPrecision.floor(1.0049999));console.log(DecimalPrecision.round(2.175495134384,7));console.log(DecimalPrecision.round(2.1753543549,8));console.log(DecimalPrecision.round(2.1755465135333,4));console.log(DecimalPrecision.ceil(17,4));console.log(DecimalPrecision.ceil(17.1,4));console.log(DecimalPrecision.ceil(17.1,15));
另一个简单的解决方案(无需编写任何函数)可以使用toFixed(),然后再次转换为float:
例如:
var objNumber = 1201203.1256546456;
objNumber = parseFloat(objNumber.toFixed(2))
从现有的答案中,我找到了另一个似乎很有效的解决方案,它也可以发送字符串,并消除尾随零。
function roundToDecimal(string, decimals) {
return parseFloat(parseFloat(string).toFixed(decimals));
}
如果你派一些公牛来,那就不算什么了。。就像“阿帕”一样。或者它可能会抛出一个错误,我认为这是正确的方法。无论如何,隐藏应该修复的错误(通过调用函数)是不好的。