我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
简单的通用舍入函数如下:
步骤如下:
使用Math.pow(10,位)将数字乘以(10乘以小数位数的幂)。使用Math.Round将结果舍入为整数。将结果除以(10乘以小数位数的幂)Math.pow(10,位)。
例子:
数字为:1.2375四舍五入至小数点后三位
1.2375 * (10^3) ==> 1.2375 * 1000 = 1237.5舍入为整数==>1238将1238除以(10^3)==>1238/1000=1.238
(注:10^3表示数学功率(10,3))。
函数编号RoundDecimal(v,n){return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(1,n)}//-------测试--------console.log(numberRoundDecimal(-0.0246411603862896567,3))//-0.025console.log(numberRoundDecimal(0.9993360575508052,3))//0.999console.log(numberRoundDecimal(1.0020739645577939,3))//1.002console.log(numberRoundDecimal(0.975,0))//1console.log(numberRoundDecimal(0.975,1))//1console.log(numberRoundDecimal(0.975,2))//0.98console.log(numberRoundDecimal(1.005,2))//1.01
其他回答
在Node.js环境中,我只使用roundTo模块:
const roundTo = require('round-to');
...
roundTo(123.4567, 2);
// 123.46
只有在必要的时候你说?
如果你也关心负数,我建议你。。。
有些答案对负数不太有效。。。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>roundPrecision</title>
<script>
class MyMath{
static roundPrecision(number, precision, fillZeros) {
// Number you want to round
// precision nb of decimals
// fillZeros the number of 0 You want to add IF necessary!
// 0 = no fill with zeros.
let num = number;
let prec = precision;
let exp = Math.pow(10, prec);
let round = Math.round(number * exp)/exp
if (fillZeros>0) {
return round.toFixed(fillZeros)
}
return round;
}
}
</script>
</head>
<body>
<p class="myMath" id="field1"></p>
<p class="myMath" id="field2"></p>
<p class="myMath" id="field3"></p>
<p class="myMath" id="field4"></p>
<p class="myMath" id="field5"></p>
<p class="myMath" id="field6"></p>
<p class="myMath" id="field7"></p>
<script>
document.getElementById("field1").innerHTML = MyMath.roundPrecision(5, 0, 3); // 5.000
document.getElementById("field2").innerHTML = MyMath.roundPrecision(Math.PI, 2, 4); // 3.1400
document.getElementById("field3").innerHTML = MyMath.roundPrecision(2.4, 1, 2); // 2.40
document.getElementById("field4").innerHTML = MyMath.roundPrecision(2.9, 0, 2); // 3.00
document.getElementById("field5").innerHTML = MyMath.roundPrecision(10, 0, 2); // 10.00
document.getElementById("field6").innerHTML = MyMath.roundPrecision(-10.5, 1, 2); // 10.00
document.getElementById("field7").innerHTML = MyMath.roundPrecision(-1.006, 2, 0); // 10.00
</script>
</body>
</html>
使用类似的方法“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
问题是四舍五入到两位小数。
让我们不要把这个复杂化,修改原型链等。
以下是单线解决方案
让round2dec=num=>数学舍入(num*100)/100;控制台日志(round2dec(1.77));控制台日志(round2dec(1.774));控制台日志(round2dec(1.777));console.log(round2dec(10));
const formattedNumber=数学舍入(数字*100)/100;