我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
尝试使用jQuery.number插件:
var number = 19.8000000007;
var res = 1 * $.number(number, 2);
其他回答
与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;
我知道有很多答案,但大多数答案在某些特定情况下都有副作用。
没有任何副作用的最简单和最短的解决方案如下:
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
这里找到的答案都不正确。臭柴塞曼要求四舍五入,但你们都四舍五进。
要进行汇总,请使用以下命令:
Math.ceil(num * 100)/100;
问题是四舍五入到两位小数。
让我们不要把这个复杂化,修改原型链等。
以下是单线解决方案
让round2dec=num=>数学舍入(num*100)/100;控制台日志(round2dec(1.77));控制台日志(round2dec(1.774));控制台日志(round2dec(1.777));console.log(round2dec(10));
使用Math.rround():
Math.round(num * 100) / 100
或者更具体地说,为了确保1.005这样的数字正确,请使用Number.EPSILON:
Math.round((num + Number.EPSILON) * 100) / 100