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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

我创建了这个函数,用于舍入数字。该值可以是字符串(例如“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

其他回答

+(10).toFixed(2); // = 10
+(10.12345).toFixed(2); // = 10.12

(10).toFixed(2); // = 10.00
(10.12345).toFixed(2); // = 10.12

一个简单的通用解决方案

常量舍入=(n,dp)=>{常量h=+('1'.padEnd(dp+1,'0'))//10或100或1000等return数学舍入(n*h)/h}console.log(“圆形(2.3454,3)”,圆形console.log(“圆形(2.3456,3)”,圆形(2.34563))//2.346console.log('圆形(2.3456,2)',圆形(2.34562))//2.35

或者只使用具有相同签名的Lodash圆-例如,_.round(2.3456,2)

使用Math.rround():

Math.round(num * 100) / 100

或者更具体地说,为了确保1.005这样的数字正确,请使用Number.EPSILON:

Math.round((num + Number.EPSILON) * 100) / 100

一个简单的解决方案是,如果你想四舍五入,可以使用Lodash的ceil函数。。。

_.round(6.001, 2)

给出6

_.ceil(6.001, 2);

给出6.01

_.ceil(37.4929, 2);

给出37.5

_.round(37.4929, 2);

给出37.49

从我在MDN上找到的precisionRound(1.005的事件返回1而不是1.01)上提出的示例开始,我编写了一个自定义precisionRound,用于管理随机精度数,1.005返回1.01。

这是一个函数:

function precisionRound(number, precision)
{
  if(precision < 0)
  {
    var factor = Math.pow(10, precision);
    return Math.round(number * factor) / factor;
  }
  else
    return +(Math.round(number + "e+"+precision)  + "e-"+precision);
}

console.log(precisionRound(1234.5678, 1));  // output: 1234.6
console.log(precisionRound(1234.5678, -1)); // output: 1230
console.log(precisionRound(1.005, 2));      // output: 1.01
console.log(precisionRound(1.0005, 2));     // output: 1
console.log(precisionRound(1.0005, 3));     // output: 1.001
console.log(precisionRound(1.0005, 4));     // output: 1.0005

对于TypeScript:

public static precisionRound(number: number, precision: number)
{
  if (precision < 0)
  {
    let factor = Math.pow(10, precision);
    return Math.round(number * factor) / factor;
  }
  else
    return +(Math.round(Number(number + "e+" + precision)) +
      "e-" + precision);
}