使用javascript舍入小数

时间:2011-04-04 06:50:22

标签: javascript decimal rounding

我需要使用javascript将十进制值舍入到小数位。

前,:

16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19

我找到了一些答案,但大多数答案都没有完成16.185到16.19 ..

8 个答案:

答案 0 :(得分:13)

(Math.round((16.185*Math.pow(10,2)).toFixed(1))/Math.pow(10,2)).toFixed(2);

如果您的值是,例如16.199正常回合将返回16.2 ...但是使用此方法您也将获得最后0,所以您看到16.20!但请记住,该值将以字符串形式返回。如果你想将它用于进一步的操作,你必须解析它:)

现在作为功能:

function trueRound(value, digits){
    return (Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits);
}

答案 1 :(得分:2)

感谢@ayk的回答,我将您的功能修改为:

function trueRound(value, digits){
    return ((Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits)) * 1;
}

只需添加“ * 1 ” 因为和你一样,正如你所写, 16.2 变成 16.20 我不需要背面的零。

答案 2 :(得分:1)

使用 -

Decimal ds=new Decimal(##.##);
String value=ds.format(inputnumber);

这将完全适用于我的情况,希望它能100%工作

答案 3 :(得分:0)

<强> [编辑] 此代码不适用于18.185之类的值,因为18.185 * Math.pow(10,2)正在评估为1818.4999999999997

Math.round(<value> * Math.pow(10,<no_of_decimal_places>)) / Math.pow(10,<no_of_decimal_places>) ;

示例: 1234.5678 - &gt; 2位小数 - &gt; 1234.57

Math.round(1234.5678 * Math.pow(10,2)) / Math.pow(10,2) ; 

答案 4 :(得分:0)

function formatNumber(myNum, numOfDec) {
        var dec = Math.pow(10, numOfDec);
        return Math.round(myNum * dec + 0.1) / dec;
}

答案 5 :(得分:0)

您用于四舍五入的代码是正确的。但要获得所需的结果,请从代码中删除.toFixed(numOfDec)。

功能:

function formatNumber(myNum,numOfDec){

    var decimal = 1
    for (i = 1; i <= numOfDec; i++)
        decimal = decimal * 10 //The value of decimal determines the number of decimals to be rounded off with (.5) up rule 
    var myFormattedNum = Math.round(myNum * decimal) / decimal
    return (myFormattedNum)
}

希望它能以某种方式帮助你:)

答案 6 :(得分:0)

parseFloat(myNum.toFixed(numOfDec))

答案 7 :(得分:0)

您可以尝试使用更简单的功能...

function roundOffTo(number, place) {
    return Math.round(number * place) / place;
}

它如何工作? 该地点可以是10、100、1000、10000等。反之将是0.1、0.01、0.001,依此类推。假设您的数字是16.185,而您的位置是100。它要做的第一件事是将数字乘以位置,即1618.5。用Math.round对其进行四舍五入将得出1619。除以该位将得出16.19。那里。 顺便说一下,今天不用担心.5问题了,它已经解决了。但是以防万一,请将Math.round(number * place)更改为Math.round(number * place + 0.1)。