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

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

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


当前回答

有一种方法可以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);
}

将工作的例外报告。

这是我的1行解决方案:Number((yourNumericValueHere).toFixed(2));

事情是这样的:

1)首先,你将. tofixed(2)应用到你想要四舍五入的小数上。注意,这将把值从number转换为字符串。所以如果你使用Typescript,它会抛出一个这样的错误:

" string类型不能赋值给number类型"

2)要返回数值或将字符串转换为数值,只需对所谓的“字符串”值应用Number()函数。

为了说明问题,请看下面的例子:

例子: 我有一个金额,有高达5位小数,我想缩短到2位小数。我是这样做的:

Var价格= 0.26453; var priceround = Number((价格).toFixed(2)); console.log('原始价格:' +价格); console.log('价格四舍五入:' + pricerounds);

@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/

我不知道为什么我不能在之前的答案上添加评论(也许我是绝望的盲人,我不知道),但我用@Miguel的答案想出了一个解决方案:

function precise_round(num,decimals) {
   return Math.round(num*Math.pow(10, decimals)) / Math.pow(10, decimals);
}

它的两条评论(来自@bighostkim和@Imre):

precise_round(1.275,2)不返回1.28的问题 precise_round(6,2)不返回6.00(正如他想要的)的问题。

我最终的解决方案如下:

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

正如你所看到的,我必须添加一点“更正”(这不是它是什么,但因为数学。round是有损的-你可以在jsfiddle.net上检查它-这是我知道如何“修复”它的唯一方法)。它在已经填充的数字上加了0.001,所以它在十进制值的右边加了一个1 3个0。所以使用起来应该是安全的。

之后,我添加了. tofixed(十进制),以始终以正确的格式输出数字(具有正确数量的小数)。

差不多就是这样了。好好使用它;)

编辑:增加了负数“更正”功能。

一轮下来

function round_down(value, decPlaces) {
    return Math.floor(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}

围捕

function round_up(value, decPlaces) {
    return Math.ceil(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}

圆的

function round_nearest(value, decPlaces) {
    return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}

合并https://stackoverflow.com/a/7641824/1889449和 https://www.kirupa.com/html5/rounding_numbers_in_javascript.htm谢谢 他们。