Format number to always show 2 decimal places

前端 未结 30 2869
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 08:17

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

number     display
------     -------
1            


        
相关标签:
30条回答
  • 2020-11-21 08:23
    Number(1).toFixed(2);         // 1.00
    Number(1.341).toFixed(2);     // 1.34
    Number(1.345).toFixed(2);     // 1.34 NOTE: See andy's comment below.
    Number(1.3450001).toFixed(2); // 1.35
    

    document.getElementById('line1').innerHTML = Number(1).toFixed(2);
    document.getElementById('line2').innerHTML = Number(1.341).toFixed(2);
    document.getElementById('line3').innerHTML = Number(1.345).toFixed(2);
    document.getElementById('line4').innerHTML = Number(1.3450001).toFixed(2);
    <span id="line1"></span>
    <br/>
    <span id="line2"></span>
    <br/>
    <span id="line3"></span>
    <br/>
    <span id="line4"></span>

    0 讨论(0)
  • 2020-11-21 08:23

    Is this what you mean?

    function showAsFloat(num, n){
          return !isNaN(+num) ? (+num).toFixed(n || 2) : num;
    }
    
    document.querySelector('#result').textContent = 
        [
         'command                      | result',
         '-----------------------------------------------',
         'showAsFloat(1);              | ' + showAsFloat(1),
         'showAsFloat(1.314);          | ' + showAsFloat(1.314),
         'showAsFloat(\'notanumber\')    | ' + showAsFloat('notanumber'),
         'showAsFloat(\'23.44567\', 3)   | ' + showAsFloat('23.44567', 3),
         'showAsFloat(2456198, 5)      | ' + showAsFloat('2456198', 5),
         'showAsFloat(0);              | ' + showAsFloat(0)
        ].join('\n');
    <pre id="result"></pre>

    0 讨论(0)
  • 2020-11-21 08:23

    parseInt(number * 100) / 100; worked for me.

    0 讨论(0)
  • 2020-11-21 08:26

    I do like:

    var num = 12.749;
    parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75
    

    Round the number with 2 decimal points, then make sure to parse it with parseFloat() to return Number, not String unless you don't care if it is String or Number.

    0 讨论(0)
  • 2020-11-21 08:27

    For modern browsers, use toLocaleString:

    var num = 1.345;
    num.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 });
    

    Specify a locale tag as first parameter to control the decimal separator. For a dot, use for example English U.S. locale:

    num.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
    

    which gives:

    1.35

    Most countries in Europe use a comma as decimal separator, so if you for example use Swedish/Sweden locale:

    num.toLocaleString("sv-SE", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
    

    it will give:

    1,35

    0 讨论(0)
  • 2020-11-21 08:28

    RegExp - alternative approach

    On input you have string (because you use parse) so we can get result by using only string manipulations and integer number calculations

    let toFix2 = (n) => n.replace(/(-?)(\d+)\.(\d\d)(\d+)/, (_,s,i,d,r)=> {
      let k= (+r[0]>=5)+ +d - (r==5 && s=='-');
      return s + (+i+(k>99)) + "." + ((k>99)?"00":(k>9?k:"0"+k));
    })
    
    
    // TESTs
    
    console.log(toFix2("1"));
    console.log(toFix2("1.341"));
    console.log(toFix2("1.345"));
    console.log(toFix2("1.005"));

    Explanation

    • s is sign, i is integer part, d are first two digits after dot, r are other digits (we use r[0] value to calc rounding)
    • k contains information about last two digits (represented as integer number)
    • if r[0] is >=5 then we add 1 to d - but in case when we have minus number (s=='-') and r is exact equal to 5 then in this case we substract 1 (for compatibility reasons - in same way Math.round works for minus numbers e.g Math.round(-1.5)==-1)
    • after that if last two digits k are greater than 99 then we add one to integer part i
    0 讨论(0)
提交回复
热议问题