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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

如果值是文本类型:

parseFloat("123.456").toFixed(2);

如果值是数字:

var numb = 123.23454;
numb = numb.toFixed(2);

有一个缺点,像1.5这样的值将给出“1.50”作为输出。@minitech建议的修复方法:

var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.

Math.round似乎是一个更好的解决方案。但事实并非如此!在某些情况下,它不会正确舍入:

Math.round(1.005 * 100)/100 // Returns 1 instead of expected 1.01!

toFixed()在某些情况下也不会正确舍入(在Chrome v.55.0.2883.87中测试)!

示例:

parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.

1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.

我想,这是因为1.555实际上就像是幕后的浮球1.55499994。

解决方案1是使用具有所需舍入算法的脚本,例如:

function roundNumber(num, scale) {
  if(!("" + num).includes("e")) {
    return +(Math.round(num + "e+" + scale)  + "e-" + scale);
  } else {
    var arr = ("" + num).split("e");
    var sig = ""
    if(+arr[1] + scale > 0) {
      sig = "+";
    }
    return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
  }
}

它也在Plunker。

注意:这并不是每个人都能通用的解决方案。有几种不同的舍入算法。您的实现可能不同,这取决于您的需求。请参见舍入。

解决方案2是避免前端计算,并从后端服务器提取舍入值。

另一种可能的解决方案,也不是防弹的。

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

在某些情况下,当您舍入像1.3549999999999998这样的数字时,它将返回错误的结果。它应该是1.35,但结果是1.36。

其他回答

使用类似于以下的方法进行汇总:

num = 519.805;
dp = Math.pow(10, 2);
num = parseFloat(num.toString().concat("1"));
rounded = Math.round((num + Number.EPSILON)* dp)/dp;

因为它会处理在最后只有一个小数点四舍五入的数字。

它可能对你有用,

Math.round(num * 100)/100;

了解toFixed和round之间的区别。您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性。

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

2022,原生,无库,现代浏览器,清晰可读。

函数循环(价值最小分数位数,最大分数位数) {const formattedValue=value.toLocaleString('en'{useGrouping:false,最小分数位数,最大分数位数})返回编号(格式化值)}console.log(圆形(21.891,2,3))//21.891console.log(round(1.8,2))//1.8,如果需要1.80,请删除“Number”函数。直接返回“formattedValue”。console.log(圆形(21.0001,0,1))//21console.log(圆形(0.875,3))//0.875

如果您碰巧已经在使用D3.js库,那么他们有一个强大的数字格式库。

舍入具体为D3舍入。

在您的案例中,答案是:

> d3.round(1.777777, 2)
1.78

> d3.round(1.7, 2)
1.7

> d3.round(1, 2)
1