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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

这可能会帮助您:

var result = Math.round(input*100)/100;

有关更多信息,您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性

其他回答

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

我回顾了这篇文章的每一个答案。以下是我对此事的看法:

常量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))}

我创建了这个函数,用于舍入数字。该值可以是字符串(例如“1.005”)或数字1.005,默认值为1,如果指定小数为2,则结果为1.01

round(value: string | number, decimals: number | string = "0"): number | null {
    return +( Math.round(Number(value + "e+"+decimals)) + "e-" + decimals);
}

用法:round(1.005,2)//1.01或用法:round('1.005',2)//1.01

最简单的方法是使用toFixed,然后使用Number函数去除尾随零:

const number = 15.5;
Number(number.toFixed(2)); // 15.5
const number = 1.7777777;
Number(number.toFixed(2)); // 1.78

parseFloat(“1.555”).toFixed(2);//返回1.55而不是1.56。

1.55是绝对正确的结果,因为在计算机中不存在1.555的精确表示。如果读数为1.555,则四舍五入至最接近的值=1.55499999999999994(64位浮点)。将这个数字四舍五入到Fixed(2)得到1.55。

如果输入为1.55499999999999,则此处提供的所有其他功能都会给出故障结果。

解决方案:在扫描前加上数字“5”,将数字舍入(更准确地说,从0开始舍入)。仅当数字真的是浮点(有小数点)时才执行此操作。

parseFloat("1.555"+"5").toFixed(2); // Returns 1.56