我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
您也可以重写Math.round函数来进行舍入校正,并为小数添加一个参数,并使用它,如:Math.round(Number,decimals)。请记住,这将覆盖内置组件Math.round,并为其提供另一个属性,而不是原始属性。
var round = Math.round;
Math.round = function (value, decimals) {
decimals = decimals || 0;
return Number(round(value + 'e' + decimals) + 'e-' + decimals);
}
然后你可以这样简单地使用它:
Math.round(1.005, 2);
https://jsfiddle.net/k5tpq3pd/3/
其他回答
另一种方法是:
number = 16.6666666;
console.log(parseFloat(number.toFixed(2)));
"16.67"
number = 16.6;
console.log(parseFloat(number.toFixed(2)));
"16.6"
number = 16;
console.log(parseFloat(number.toFixed(2)));
"16"
.toFixed(2)返回一个正好有两个小数点的字符串,可以是尾随零,也可以不是尾随零。执行parseFloat()将消除那些尾随的零。
这对我(TypeScript)起到了作用:
round(decimal: number, decimalPoints: number): number{
let roundedValue = Math.round(decimal * Math.pow(10, decimalPoints)) / Math.pow(10, decimalPoints);
console.log(`Rounded ${decimal} to ${roundedValue}`);
return roundedValue;
}
样本输出
Rounded 18.339840000000436 to 18.34
Rounded 52.48283999999984 to 52.48
Rounded 57.24612000000036 to 57.25
Rounded 23.068320000000142 to 23.07
Rounded 7.792980000000398 to 7.79
Rounded 31.54157999999981 to 31.54
Rounded 36.79686000000004 to 36.8
Rounded 34.723080000000124 to 34.72
Rounded 8.4375 to 8.44
Rounded 15.666960000000074 to 15.67
Rounded 29.531279999999924 to 29.53
Rounded 8.277420000000006 to 8.28
与Brian Ustas建议的使用Math.round不同,我更喜欢Math.trunc方法来解决以下问题:
const twoDecimalRound = num => Math.round(num * 100) / 100;
const twoDecimalTrunc = num => Math.trunc(num * 100) / 100;
console.info(twoDecimalRound(79.996)); // Not desired output: 80;
console.info(twoDecimalTrunc(79.996)); // Desired output: 79.99;
我回顾了这篇文章的每一个答案。以下是我对此事的看法:
常量nbRounds=7;常量舍入=(x,n=2)=>{常量精度=数学.pw(10,n)return数学舍入((x+Number.EPSILON)*precision)/精度;}设i=0;而(nbRounds>i++){console.log(“round(1.00083899,”,i,“)>”,round(1.00 08389,i))console.log(“圆形(1.83999305,”,i,“)>”,圆形(1.83999305,i))}
简单的通用舍入函数如下:
步骤如下:
使用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