JavaScript数学,四舍五入到小数点后两位[重复]

本文翻译自:JavaScript math, round to two decimal places [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 2 years ago . 2年前关闭。

I have the following JavaScript syntax: 我有以下JavaScript语法:

var discount = Math.round(100 - (price / listprice) * 100);

This rounds up to the whole number. 这四舍五入为整数。 How can I return the result with two decimal places? 如何返回两位小数的结果?


#1楼

参考:https://stackoom.com/question/148cC/JavaScript数学-四舍五入到小数点后两位-重复


#2楼

NOTE - See Edit 4 if 3 digit precision is important 注-如果3位数精度很重要,请参阅编辑4

var discount = (price / listprice).toFixed(2);

toFixed will round up or down for you depending on the values beyond 2 decimals. toFixed将为您舍入或舍入,具体取决于2位小数之后的值。

Example: http://jsfiddle.net/calder12/tv9HY/ 示例: http//jsfiddle.net/calder12/tv9HY/

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed 文档: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Edit - As mentioned by others this converts the result to a string. 编辑 -正如其他人所提到的,它将结果转换为字符串。 To avoid this: 为了避免这种情况:

var discount = +((price / listprice).toFixed(2));

Edit 2 - As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. 编辑2-正如注释中所提到的,此函数在某种程度上会失败,例如在1.005的情况下,它将返回1.00而不是1.01。 If accuracy to this degree is important I've found this answer: https://stackoverflow.com/a/32605063/1726511 Which seems to work well with all the tests I've tried. 如果准确性在这个程度上很重要,那么我已经找到了这个答案: https : //stackoverflow.com/a/32605063/1726511这似乎与我尝试过的所有测试均能很好地工作。

There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices. 不过,需要进行一些小的修改,上面链接的答案中的函数在四舍五入时返回整数,因此例如99.004将返回99而不是99.00,这对于显示价格而言并不理想。

Edit 3 - Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. 编辑3-似乎在实际收益表上固定了TOST仍在搞砸一些数字,此最终编辑似乎有效。 Geez so many reworks! 哎呀,这么多返工!

   var discount = roundTo((price / listprice), 2);

   function roundTo(n, digits) {
     if (digits === undefined) {
       digits = 0;
     }

     var multiplicator = Math.pow(10, digits);
     n = parseFloat((n * multiplicator).toFixed(11));
     var test =(Math.round(n) / multiplicator);
     return +(test.toFixed(digits));
   }

See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/ 请参阅此处的小提琴示例: https : //jsfiddle.net/calder12/3Lbhfy5s/

Edit 4 - You guys are killing me. 编辑4-你们杀了我。 Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result. Edit 3对负数失败,而没有深入研究为什么在进行舍入之前将负数变为正数更容易处理,然后在返回结果之前将其变回正好。

function roundTo(n, digits) {
    var negative = false;
    if (digits === undefined) {
        digits = 0;
    }
        if( n < 0) {
        negative = true;
      n = n * -1;
    }
    var multiplicator = Math.pow(10, digits);
    n = parseFloat((n * multiplicator).toFixed(11));
    n = (Math.round(n) / multiplicator).toFixed(2);
    if( negative ) {    
        n = (n * -1).toFixed(2);
    }
    return n;
}

Fiddle: https://jsfiddle.net/3Lbhfy5s/79/ 小提琴: https : //jsfiddle.net/3Lbhfy5s/79/


#3楼

尝试使用discount.toFixed(2);


#4楼

To get the result with two decimals, you can do like this : 要获得两个小数点的结果,可以这样:

var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;

The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result. 要取整的值乘以100以保留前两位数字,然后我们除以100得到实际结果。


#5楼

If you use a unary plus to convert a string to a number as documented on MDN . 如果您使用一元加号将字符串转换为MDN上记录的数字。

For example: +discount.toFixed(2) 例如: +discount.toFixed(2)


#6楼

A small variation on the accepted answer. 接受的答案略有不同。 toFixed(2) returns a string, and you will always get two decimal places. toFixed(2)返回一个字符串,并且您将始终得到两个小数位。 These might be zeros. 这些可能为零。 If you would like to suppress final zero(s), simply do this: 如果您想取消最后的零,只需执行以下操作:

var discount = + ((price / listprice).toFixed(2));

Edited: I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values. 编辑:我刚刚发现了Firefox 35.0.1中的一个bug,这意味着以上内容可能为NaN提供了一些值。
I've changed my code to 我已将代码更改为

var discount = Math.round(price / listprice * 100) / 100;

This gives a number with up to two decimal places. 这给出了一个最多有两个小数位的数字。 If you wanted three, you would multiply and divide by 1000, and so on. 如果要三个,则可以乘以1000,以此类推。
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first. OP总是希望小数点后两位,但是如果toFixed()在Firefox中损坏,则需要先修复。
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388 参见https://bugzilla.mozilla.org/show_bug.cgi?id=1134388

JavaScript中,我们可以使用toFixed()方法来进行小数点四舍五入。这个方法可以把一个数字四舍五入为指定小数位数的数字。例如,如果我们想要保留两位小数,我们可以使用toFixed(2)。不过需要注意的是,这个方法使用的是银行家舍入规则,而不是数学中的四舍五入规则。银行家舍入规则是一种四舍六入五取偶的方法,具体规则如下:当要舍弃的位数小于5时,直接舍弃;当要舍弃的位数大于5时,直接进位;当要舍弃的位数等于5时,如果5后面还有非零数字,则进位;如果5后面没有非零数字,则根据5前面的数字的奇偶性来判断是否进位。这种规则可以避免舍入误差的累积,更加精确。在JavaScript中,我们还可以使用其他方法来进行小数点四舍五入。例如,我们可以通过重写Number类型的toFixed方法来修改其默认行为。具体实现代码如下所示:Number.prototype.toFixed = function(d) { var s = this + ""; if (!d) d = 0; if (s.indexOf(".") == -1) s += "."; s += new Array(d + 1).join("0"); if (new RegExp("^(-|\\ )?(\\d(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) { var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true; if (a == d + 2) { a = s.match(/\d/g); if (parseInt(a[a.length - 1]) > 4) { for (var i = a.length - 2; i >= 0; i--) { a[i] = parseInt(a[i]) + 1; if (a[i] == 10) { a[i] = 0; b = i != 1; } else break; } } s = a.join("").replace(new RegExp("(\\d)(\\d{" + d + "})\\d$"), "$1.$2"); } if (b) s = s.substr(1); return (pm + s).replace(/\.$/, ""); } return this + ""; };如果你只是想保留两位小数,可以使用以下代码:var num = 2; var roundedNum = num.toFixed(2); console.log(roundedNum); // 输出2.00
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值