Js format the amount to set the reserved number of decimal places

  • 2020-03-30 02:52:30
  • OfStack

 
//The format s of the amount is the parameter to be formatted (floating point type), and n is the number of digits reserved after the decimal point
function formatMoney(s,n){ 
n = n>0 && n<=20 ? n : 2; 
s = parseFloat((s+"").replace(/[^d.-]/g,"")).toFixed(n)+""; 
var l = s.split(".")[0].split("").reverse(), 
r = s.split(".")[1]; 
t = ""; 
for(i = 0;i<l.length;i++){ 
t+=l[i]+((i+1)%3==0 && (i+1) != l.length ? "," : ""); 
} 
return t.split("").reverse().join("")+"."+r; 
} 

Related articles: