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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

所有浏览器和精度的通用答案:

function round(num, places) {
    if(!places) {
        return Math.round(num);
    }

    var val = Math.pow(10, places);
    return Math.round(num * val) / val;
}

round(num, 2);

其他回答

在Node.js环境中,我只使用roundTo模块:

const roundTo = require('round-to');
...
roundTo(123.4567, 2);

// 123.46

如果您不想舍入,请使用以下函数。

function ConvertToDecimal(num) {
  num = num.toString(); // If it's not already a String
  num = num.slice(0, (num.indexOf(".")) + 3); // With 3 exposing the hundredths place    
alert('M : ' + Number(num)); // If you need it back as a Number     
}

下面是一个原型方法:

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

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

使用此函数Number(x).toFixed(2);

只有在必要时才能实现这种舍入的一种方法是使用Number.protype.toLocaleString():

myNumber.toLocaleString('en', {maximumFractionDigits:2, useGrouping:false})

这将提供您期望的输出,但是是字符串。如果不是您期望的数据类型,您仍然可以将它们转换回数字。