首页 文章

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

提问于
浏览
345

这个问题在这里已有答案:

我有以下JavaScript语法:

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

这可以达到整数 . 如何以小数点后两位返回结果?

13 回答

  • 5

    NOTE - See Edit 4 if 3 digit precision is important

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

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

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

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

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

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

    Edit 2 - 正如评论中所提到的,这个函数在一些精度上失败了,例如在1.005的情况下,它将返回1.00而不是1.01 . 如果这个程度的准确性很重要,我找到了这个答案:https://stackoverflow.com/a/32605063/1726511这似乎与我尝试的所有测试都很好 .

    虽然需要一个小的修改,上面链接的答案中的函数在它舍入为1时返回整数,所以例如99.004将返回99而不是99.00,这不是显示价格的理想选择 .

    Edit 3 - 似乎在实际返回时有toFixed是STILL搞砸了一些数字,这个最终编辑似乎有效 . Geez这么多的返工!

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

    请参见此处的小提琴示例:https://jsfiddle.net/calder12/3Lbhfy5s/

    Edit 4 - 你们是在杀我编辑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;
    }
    

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

  • 39

    如果使用一元加号将字符串转换为数字as documented on MDN .

    例如: +discount.toFixed(2)

  • 10

    Math.round()和.toFixed()函数用于舍入到最接近的整数 . 处理小数并使用Math.round()的“multiply and divide”方法或.toFixed()的参数时,会得到不正确的结果 . 例如,如果您尝试使用Math.round(1.005 * 100)/ 100对1.005进行舍入,那么您将使用.toFixed(2)获得1和1.00的结果,而不是获得1.01的正确答案 .

    您可以使用以下方法来解决此问题:

    Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
    

    添加.toFixed(2)以获得您想要的两个小数位 .

    Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
    

    你可以创建一个函数来处理舍入:

    function round(value, decimals) {
        return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
    }
    

    示例:https://jsfiddle.net/k5tpq3pd/36/

    Alternativ

    您可以使用原型向Number添加圆函数 . 我不建议在这里添加.toFixed(),因为它会返回一个字符串而不是数字 .

    Number.prototype.round = function(decimals) {
        return Number((Math.round(this + "e" + decimals)  + "e-" + decimals));
    }
    

    并像这样使用它:

    var numberToRound = 100 - (price / listprice) * 100;
    numberToRound.round(2);
    numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
    

    示例https://jsfiddle.net/k5tpq3pd/35/

    资料来源:http://www.jacklmoore.com/notes/rounding-in-javascript/

  • 29

    要获得两位小数的结果,您可以这样做:

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

    要舍入的值乘以100以保持前两位数,然后我们除以100以得到实际结果 .

  • 14

    尝试使用 discount.toFixed(2);

  • 10

    我认为我看到它的最好方法是将数字乘以10乘以数字,然后再进行Math.round,最后将数字除以10 . 这是我在打字稿中使用的一个简单函数:

    function roundToXDigits(value: number, digits: number) {
        value = value * Math.pow(10, digits);
        value = Math.round(value);
        value = value / Math.pow(10, digits);
        return value;
    }
    

    或者简单的javascript:

    function roundToXDigits(value, digits) {
        if(!digits){
            digits = 2;
        }
        value = value * Math.pow(10, digits);
        value = Math.round(value);
        value = value / Math.pow(10, digits);
        return value;
    }
    
  • 663

    我找到的最好和最简单的解决方案是

    function round(value, decimals) {
     return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
    }   
    round(1.005, 2); // 1.01
    
  • 120

    接受答案的一个小变化 . toFixed(2) 返回一个字符串,您将始终获得两个小数位 . 这些可能是零 . 如果你想压制最终零(s),只需这样做:

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

    编辑:我刚刚发现Firefox 35.0.1中似乎是一个错误,这意味着上面的内容可能会给NaN一些值 .
    我已将代码更改为

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

    这给出了一个最多两位小数的数字 . 如果你想要三个,你会乘以除以1000,依此类推 .
    OP总是想要两位小数,但如果在Firefox中使用toFixed(),则需要先修复 .
    https://bugzilla.mozilla.org/show_bug.cgi?id=1134388

  • 0

    Fastest Way - 比toFixed()更快:

    两个十进制

    x      = .123456
    result = Math.round(x * 100) / 100  // result .12
    

    三个十分之一

    x      = .123456
    result = Math.round(x * 1000) / 1000      // result .123
    
  • 2
    function round(num,dec)
        {
          num = Math.round(num+'e'+dec)
          return Number(num+'e-'+dec)
        }
          //Round to a decimal of your choosing:
        round(1.3453,2)
    
  • -1

    要处理舍入到任意数量的小数位,具有2行代码的函数将满足大多数需求 . 这是一些可以使用的示例代码 .

    var testNum = 134.9567654;
        var decPl = 2;
        var testRes = roundDec(testNum,decPl);  
        alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
    
        function roundDec(nbr,dec_places){
            var mult = Math.pow(10,dec_places);
            return Math.round(nbr * mult) / mult;
        }
    
  • 7
    function discoverOriginalPrice(discountedPrice, salePercentage) {
      var originalPrice = discountedPrice / (1 - (salePercentage * .01));
      return +originalPrice.toFixed(2);
    }
    
  • 0

    这是一个有效的例子

    var value=200.2365455;
    result=Math.round(value*100)/100    //result will be 200.24
    

相关问题