本文介绍了JavaScript数学,舍入到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JavaScript语法:

I have the following JavaScript syntax:

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?

推荐答案

注意 - 如果3位精度很重要,请参阅编辑4

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

toFixed会根据超过2位小数的值向上或向下舍入。

toFixed will round up or down for you depending on the values beyond 2 decimals.

示例:

文档:

编辑 - 正如其他人所说,这会将结果转换为字符串。为了避免这种情况:

Edit - As mentioned by others this converts the result to a string. To avoid this:

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

编辑2 - 正如评论中所提到的,这个功能在某些方面失败了精度,例如在1.005的情况下,它将返回1.00而不是1.01。如果这个程度的准确性很重要我找到了答案:

See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/

编辑4 - 你们是在杀我编辑3在负数上失败,没有深入研究为什么在进行四舍五入之前处理将负数转为正数然后在返回结果之前将其转回来更容易。

Edit 4 - You guys are killing me. 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.

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

小提琴:

这篇关于JavaScript数学,舍入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 09:24
查看更多