Format number to always show 2 decimal places

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

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

提交回复
热议问题