我想最多四舍五入两位小数,但只有在必要时。

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

这对我(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

其他回答

在这里,我使用了三元运算符来检查数字是否具有小数。如果没有,我只需返回数字。

否则,我使用Intl.NumberFormat构造函数获取所需的值。

Intl.NumberFormat是ECMAScript国际化API规范(ECMA402)的一部分。它有很好的浏览器支持,甚至包括IE11,并且在Node.js中完全支持。

const numberFormatter=新Intl.NumberFormat('en-US'{minimumFractionDigits:2,最大分数位数:2,});函数getRoundedNumber(number){return number.toString().indexOf(“.”)==-1?number:numberFormatter.format(数字);}console.log(getRoundedNumber(10));console.log(getRoundedNumber(1.7777777));console.log(getRoundedNumber(9.1));console.log(getRoundedNumber(2.345));console.log(getRoundedNumber(2.2095));console.log(getRoundedNumber(2.995));

虽然建议的答案通常是正确的,但没有考虑传入的数字的精度,这在原始问题中没有表示为要求,但在科学应用的情况下,这可能是一个要求,其中3不同于3.00(例如)。

事实上,建议的答案是3.001到3,而保持数字精度的信息应该是3.00。

下面是一个考虑到这一点的函数:

函数roundTo(值,十进制){让absValue=Math.abs(值);let int=数学地板(absValue).toString().length;let dec=absValue.toString().length-int;dec-=(Number.isIInteger(absValue)?0 : 1);返回值toPrecision(int+Math.min(dec,十进制));}

与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;

如果您需要将货币金额格式化为整数货币或包含小数货币部分的金额,则会有一点不同。

例如:

1应输出$1

1.1应产出1.10美元

1.01应产出1.01美元

假设金额是一个数字:

常量格式amount=(amount)=>amount%1==0?amount:amount.toFixed(2);

如果amount不是数字,则使用parseFloat(amount)将其转换为数字。

这对我(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