Format number to always show 2 decimal places

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

    function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
      var numbers = string.toString().match(/\d+/g).join([]);
      numbers = numbers.padStart(decimals+1, "0");
      var splitNumbers = numbers.split("").reverse();
      var mask = '';
      splitNumbers.forEach(function(d,i){
        if (i == decimals) { mask = decimal + mask; }
        if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
        mask = d + mask;
      });
      return pre + mask + pos;
    }
    var element = document.getElementById("format");
    var money= number_format("10987654321",2,',','.');
    element.innerHTML = money;
    #format{
    display:inline-block;
    padding:10px;
    border:1px solid #ffffd;
    background:#f5f5f5;
    }
    Test 123456789

提交回复
热议问题