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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

根据评论中已给出的答案,链接至http://jsfiddle.net/AsRqx/,下面的一个对我来说很好。

function C(num)
{
    return +(Math.round(num + "e+2") + "e-2");
}

function N(num, places)
{
    return +(Math.round(num + "e+" + places) + "e-" + places);
}

C(1.005);

N(1.005, 0);
N(1.005, 1); // Up to 1 decimal places
N(1.005, 2); // Up to 2 decimal places
N(1.005, 3); // Up to 3 decimal places

其他回答

这是我想出的一个函数,用来进行“舍入”。我使用了double Math.round来补偿JavaScript的不准确乘法,因此1.005将正确舍入为1.01。

function myRound(number, decimalplaces){
    if(decimalplaces > 0){
        var multiply1 = Math.pow(10,(decimalplaces + 4));
        var divide1 = Math.pow(10, decimalplaces);
        return Math.round(Math.round(number * multiply1)/10000 )/divide1;
    }
    if(decimalplaces < 0){
        var divide2 = Math.pow(10, Math.abs(decimalplaces));
        var multiply2 = Math.pow(10, Math.abs(decimalplaces));
        return Math.round(Math.round(number / divide2) * multiply2);
    }
    return Math.round(number);
}

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

舍入具体为D3舍入。

在您的案例中,答案是:

> d3.round(1.777777, 2)
1.78

> d3.round(1.7, 2)
1.7

> d3.round(1, 2)
1

我在MDN上找到了这个。他们的方法避免了前面提到的1.005的问题。

函数roundToTwo(num){return+(数学舍入(num+“e+2”)+“e-2”);}console.log(“1.005=>”,roundToTwo(1.005));console.log('10=>',roundToTwo(10));console.log('1.7777777=>',roundToTwo(1.7777777));console.log('9.1=>',roundToTwo(9.1));console.log('1234.5678=>',roundToTwo(1234.5678));

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

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     
}

使用Math.rround():

Math.round(num * 100) / 100

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

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