Format number to always show 2 decimal places

前端 未结 30 2825
爱一瞬间的悲伤
爱一瞬间的悲伤 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:29
    (Math.round(num * 100) / 100).toFixed(2);
    

    Live Demo

    var num1 = "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>

    Note that it will round to 2 decimal places, so the input 1.346 will return 1.35.

    0 讨论(0)
  • 2020-11-21 08:29
    var number = 123456.789;
    
    
    console.log(new Intl.NumberFormat('en-IN', { maximumFractionDigits: 2 }).format(number));
    

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

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

    Convert a number into a string, keeping only two decimals:

    var num = 5.56789;
    var n = num.toFixed(2);
    

    The result of n will be:

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

    Where specific formatting is required, you should write your own routine or use a library function that does what you need. The basic ECMAScript functionality is usually insufficient for displaying formatted numbers.

    A thorough explanation of rounding and formatting is here: http://www.merlyn.demon.co.uk/js-round.htm#RiJ

    As a general rule, rounding and formatting should only be peformed as a last step before output. Doing so earlier may introduce unexpectedly large errors and destroy the formatting.

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

    You can try this code:

        function FormatNumber(number, numberOfDigits = 2) {
            try {
                return new Intl.NumberFormat('en-US').format(parseFloat(number).toFixed(2));
            } catch (error) {
                return 0;
            }
        }
    
        var test1 = FormatNumber('1000000.4444');
        alert(test1); // 1,000,000.44
    
        var test2 = FormatNumber(100000000000.55555555, 4);
        alert(test2); // 100,000,000,000.56
    
    0 讨论(0)
  • 2020-11-21 08:31
    function currencyFormat (num) {
        return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
    }
    
    console.info(currencyFormat(2665));   // $2,665.00
    console.info(currencyFormat(102665)); // $102,665.00
    
    0 讨论(0)
提交回复
热议问题