这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的:10.8、2.4等等。这些都不是我的小数点后两位的想法,所以我怎么能改善以下?

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

我想要10.80、2.40等数字。jQuery的使用对我来说很好。


当前回答

Number(((Math.random() * 100) + 1).toFixed(2))

这将返回一个从1到100四舍五入到小数点后2位的随机数。

其他回答

有一种方法可以100%确定你得到的数字有两个小数:

(Math.round(num*100)/100).toFixed(2)

如果这会导致舍入误差,你可以使用James在他的评论中解释的以下方法:

(Math.round((num * 1000)/10)/100).toFixed(2)

我通常把它添加到我的个人库中,在一些建议和使用@TIMINeutron解决方案之后,并使其适用于十进制长度,这一个最适合:

function precise_round(num, decimals) {
   var t = Math.pow(10, decimals);   
   return (Math.round((num * t) + (decimals>0?1:0)*(Math.sign(num) * (10 / Math.pow(100, decimals)))) / t).toFixed(decimals);
}

将工作的例外报告。

您还可以使用. toprecision()方法和一些自定义代码,无论int部分的长度如何,始终四舍五入到十进制第n位。

function glbfrmt (number, decimals, seperator) {
    return typeof number !== 'number' ? number : number.toPrecision( number.toString().split(seperator)[0].length + decimals);
}

你也可以让它成为一个插件,以便更好地使用。

这里有一个简单的例子

function roundFloat(num,dec){
    var d = 1;
    for (var i=0; i<dec; i++){
        d += "0";
    }
    return Math.round(num * d) / d;
}

使用like alert(roundFloat(1.79209243929,4));

杰斯菲德尔

@heridev和我用jQuery创建了一个小函数。

接下来你可以试试:

HTML

<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">​

jQuery

// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
    $('.two-digits').keyup(function(){
        if($(this).val().indexOf('.')!=-1){         
            if($(this).val().split(".")[1].length > 2){                
                if( isNaN( parseFloat( this.value ) ) ) return;
                this.value = parseFloat(this.value).toFixed(2);
            }  
         }            
         return this; //for chaining
    });
});

​ 在线演示:

http://jsfiddle.net/c4Wqn/