Js amount format back and forth conversion example

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

Here's an example:
 
function fmoney(s, n) //S: passed in float, n: want to return a few decimal places
{ 
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; 
} 

What this function does is

Call: fmoney("12345.675910", 3), return 12,345.676
 
function rmoney(s) 
{ 
return parseFloat(s.replace(/[^d.-]/g, "")); 
} 

Return the number in the amount format above as float.
 
rmoney(12,345.676) //The result returned is: 12345.676

Related articles: