Format number to always show 2 decimal places

前端 未结 30 2824
爱一瞬间的悲伤
爱一瞬间的悲伤 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:35

    Extend Math object with precision method

    Object.defineProperty(Math, 'precision',{
       value: function (value,precision,type){
                 var v = parseFloat(value),
                     p = Math.max(precision,0)||0,
                     t = type||'round';
                  return (Math[t](v*Math.pow(10,p))/Math.pow(10,p)).toFixed(p);
              }
        });
    
    console.log(
        Math.precision(3.1,3), // round 3 digits 
        Math.precision(0.12345,2,'ceil'), // ceil 2 digits
        Math.precision(1.1) // integer part
    )

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

    var num1 = "0.1";
    document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);
    
    var num2 = "1.341";
    document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);
    
    var num3 = "1.345";
    document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
    span {
        border: 1px solid #000;
        margin: 5px;
        padding: 5px;
    }
    <span id="num1"></span>
    <span id="num2"></span>
    <span id="num3"></span>

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

    I had to decide between the parseFloat() and Number() conversions before I could make toFixed() call. Here's an example of a number formatting post-capturing user input.

    HTML:

    <input type="number" class="dec-number" min="0" step="0.01" />
    

    Event handler:

    $('.dec-number').on('change', function () {
         const value = $(this).val();
         $(this).val(value.toFixed(2));
    });
    

    The above code will result in TypeError exception. Note that although the html input type is "number", the user input is actually a "string" data type. However, toFixed() function may only be invoked on an object that is a Number.

    My final code would look as follows:

    $('.dec-number').on('change', function () {
         const value = Number($(this).val());
         $(this).val(value.toFixed(2));
    });
    

    The reason I favor to cast with Number() vs. parseFloat() is because I don't have to perform an extra validation neither for an empty input string, nor NaN value. The Number() function would automatically handle an empty string and covert it to zero.

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

    You are not giving us the whole picture.

    javascript:alert(parseFloat(1).toFixed(2)) shows 1.00 in my browsers when I paste it int0 the location bar. However if you do something to it afterwards, it will revert.

    var num = 2
    document.getElementById('spanId').innerHTML=(parseFloat(num).toFixed(2)-1)
    
    
    shows 1 and not 1.00
    
    0 讨论(0)
  • 2020-11-21 08:40

    If you're already using jQuery, you could look at using the jQuery Number Format plugin.

    The plugin can return formatted numbers as a string, you can set decimal, and thousands separators, and you can choose the number of decimals to show.

    $.number( 123, 2 ); // Returns '123.00'
    

    You can also get jQuery Number Format from GitHub.

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

    Simplest answer:

    var num = 1.2353453;
    num.toFixed(2); // 1.24
    

    Example: http://jsfiddle.net/E2XU7/

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