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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

要在小数位置pos(不包括小数)舍入,请执行Math.rround(num*Math.pow(10,pos))/Math.pow(1,pos

var控制台={日志:函数{document.getElementById(“控制台”).innerHTML+=s+“<br/>”}}var roundDecimals=函数(num,pos){return(Math.round(num*Math.pow(10,pos))/Math.pop(10,pos));}//https://en.wikipedia.org/wiki/Pivar pi=3.14159265358979323846264338327950288419716939937510;对于(var i=2;i<15;i++)console.log(“pi=”+roundDecimals(pi,i));对于(var i=15;i>=0;--i)console.log(“pi=”+roundDecimals(pi,i));<div id=“console”/>

其他回答

可以使用.toFixed(小数位数)。

var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23
var roundUpto = function(number, upto){
    return Number(number.toFixed(upto));
}
roundUpto(0.1464676, 2);

toFixed(2):这里2是我们要舍入的位数。

这里有一个简单的方法:

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);
}

尝试使用jQuery.number插件:

var number = 19.8000000007;
var res = 1 * $.number(number, 2);

这是我想出的一个函数,用来进行“舍入”。我使用了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);
}