Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2279
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

相关标签:
30条回答
  • 2020-11-21 06:42

    I usually add this to my personal library, and after some suggestions and using the @TIMINeutron solution too, and making it adaptable for decimal length then, this one fits best:

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

    will work for the exceptions reported.

    0 讨论(0)
  • 2020-11-21 06:42

    toFixed(n) provides n length after the decimal point; toPrecision(x) provides x total length.

    Use this method below

    // Example: toPrecision(4) when the number has 7 digits (3 before, 4 after)
        // It will round to the tenths place
        num = 500.2349;
        result = num.toPrecision(4); // result will equal 500.2
    

    AND if you want the number to be fixed use

    result = num.toFixed(2);
    
    0 讨论(0)
  • 2020-11-21 06:43

    I didn't find an accurate solution for this problem, so I created my own:

    function inprecise_round(value, decPlaces) {
      return Math.round(value*Math.pow(10,decPlaces))/Math.pow(10,decPlaces);
    }
    
    function precise_round(value, decPlaces){
        var val = value * Math.pow(10, decPlaces);
        var fraction = (Math.round((val-parseInt(val))*10)/10);
    
        //this line is for consistency with .NET Decimal.Round behavior
        // -342.055 => -342.06
        if(fraction == -0.5) fraction = -0.6;
    
        val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
        return val;
    }
    

    Examples:

    function inprecise_round(value, decPlaces) {
      return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
    }
    
    function precise_round(value, decPlaces) {
      var val = value * Math.pow(10, decPlaces);
      var fraction = (Math.round((val - parseInt(val)) * 10) / 10);
    
      //this line is for consistency with .NET Decimal.Round behavior
      // -342.055 => -342.06
      if (fraction == -0.5) fraction = -0.6;
    
      val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
      return val;
    }
    
    // This may produce different results depending on the browser environment
    console.log("342.055.toFixed(2)         :", 342.055.toFixed(2)); // 342.06 on Chrome & IE10
    
    console.log("inprecise_round(342.055, 2):", inprecise_round(342.055, 2)); // 342.05
    console.log("precise_round(342.055, 2)  :", precise_round(342.055, 2));   // 342.06
    console.log("precise_round(-342.055, 2) :", precise_round(-342.055, 2));  // -342.06
    
    console.log("inprecise_round(0.565, 2)  :", inprecise_round(0.565, 2));   // 0.56
    console.log("precise_round(0.565, 2)    :", precise_round(0.565, 2));     // 0.57

    0 讨论(0)
  • 2020-11-21 06:44

    This is very simple and works just as well as any of the others:

    function parseNumber(val, decimalPlaces) {
        if (decimalPlaces == null) decimalPlaces = 0
        var ret = Number(val).toFixed(decimalPlaces)
        return Number(ret)
    }
    

    Since toFixed() can only be called on numbers, and unfortunately returns a string, this does all the parsing for you in both directions. You can pass a string or a number, and you get a number back every time! Calling parseNumber(1.49) will give you 1, and parseNumber(1.49,2) will give you 1.50. Just like the best of 'em!

    0 讨论(0)
  • 2020-11-21 06:45

    One way to be 100% sure that you get a number with 2 decimals:

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

    If this causes rounding errors, you can use the following as James has explained in his comment:

    (Math.round((num * 1000)/10)/100).toFixed(2)
    
    0 讨论(0)
  • 2020-11-21 06:46

    parse = function (data) {
           data = Math.round(data*Math.pow(10,2))/Math.pow(10,2);
           if (data != null) {
                var lastone = data.toString().split('').pop();
                if (lastone != '.') {
                     data = parseFloat(data);
                }
           }
           return data;
      };
    
    $('#result').html(parse(200)); // output 200
    $('#result1').html(parse(200.1)); // output 200.1
    $('#result2').html(parse(200.10)); // output 200.1
    $('#result3').html(parse(200.109)); // output 200.11
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <div id="result"></div>
    <div id="result1"></div>
    <div id="result2"></div>
    <div id="result3"></div>

    0 讨论(0)
提交回复
热议问题