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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

另一种方法是:

number = 16.6666666;
console.log(parseFloat(number.toFixed(2)));
"16.67"

number = 16.6;
console.log(parseFloat(number.toFixed(2)));
"16.6"

number = 16;
console.log(parseFloat(number.toFixed(2)));
"16"

.toFixed(2)返回一个正好有两个小数点的字符串,可以是尾随零,也可以不是尾随零。执行parseFloat()将消除那些尾随的零。

其他回答

const formattedNumber=数学舍入(数字*100)/100;

下面是一个原型方法:

Number.prototype.round = function(places){
    places = Math.pow(10, places); 
    return Math.round(this * places)/places;
}

var yournum = 10.55555;
yournum = yournum.round(2);

2017只需使用本机代码.toFixed()

number = 1.2345;
number.toFixed(2) // "1.23"

如果您需要严格要求并在需要时添加数字,可以使用替换

number = 1; // "1"
number.toFixed(5).replace(/\.?0*$/g,'');

更简单的ES6方法是

const round = (x, n) => 
  Number(parseFloat(Math.round(x * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n));

此模式还返回要求的精度。

ex:

round(44.7826456, 4)  // yields 44.7826
round(78.12, 4)       // yields 78.12

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

舍入具体为D3舍入。

在您的案例中,答案是:

> d3.round(1.777777, 2)
1.78

> d3.round(1.7, 2)
1.7

> d3.round(1, 2)
1