I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1
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