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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

从我在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);
}

其他回答

要不处理许多0,请使用以下变体:

Math.round(num * 1e2) / 1e2

问题是四舍五入到两位小数。

让我们不要把这个复杂化,修改原型链等。

以下是单线解决方案

让round2dec=num=>数学舍入(num*100)/100;控制台日志(round2dec(1.77));控制台日志(round2dec(1.774));控制台日志(round2dec(1.777));console.log(round2dec(10));

有一种解决方案适用于所有数字。试试看。表达式如下所示。

Math.round((num + 0.00001) * 100) / 100. 

Try Below Ex:

Math.round((1.005 + 0.00001) * 100) / 100 
Math.round((1.0049 + 0.00001) * 100) / 100

我最近测试了所有可能的解决方案,并在尝试了近10次后最终得出了结果。

这是计算过程中出现的问题的屏幕截图,

.

转到金额字段。它几乎无限地回归。我尝试了toFixed()方法,但它在某些情况下不起作用(例如,尝试使用pi),最后导出了上面给出的解决方案。

这里有一个简单的方法:

Math.round(value * 100) / 100

不过,您可能需要继续创建一个单独的函数来为您执行此操作:

function roundToTwo(value) {
    return(Math.round(value * 100) / 100);
}

然后,只需传入值。

通过添加第二个参数,可以将其增强为任意小数位数。

function myRound(value, places) {
    var multiplier = Math.pow(10, places);

    return (Math.round(value * multiplier) / multiplier);
}
+(10).toFixed(2); // = 10
+(10.12345).toFixed(2); // = 10.12

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