[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1529
  • Last Modified:

Function to convert between currency (formatted) and float (non-formatted)

Hello,

I am looking for two functions.  One that can be passed a floating point number (ex: 1234.56) and returns the number formatted as currency ($1,234.56) AND the reverse function ($1,234.56 -> 1234.56)

I'm (nearly) certain that the solution would make use of regular expressions, so even just having the proper expressions would be adequate

Validation of the input is not necessary (I can do that separately) ...

Thanks!
0
Argblat
Asked:
Argblat
2 Solutions
 
TertioptusCommented:
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}

to do the reverse, just replace the '$' and the ',' with an empty string ("");

something like this.value.replace("$","").replace(",","")
0
 
DigitalTyrantCommented:
function formatCurrency(strValue)
{
      strValue = strValue.toString().replace(/\$|\,/g,'');
      dblValue = parseFloat(strValue);

      blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
      dblValue = Math.floor(dblValue*100+0.50000000001);
      intCents = dblValue%100;
      strCents = intCents.toString();
      dblValue = Math.floor(dblValue/100).toString();
      if(intCents<10)
            strCents = "0" + strCents;
      for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
            dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
            dblValue.substring(dblValue.length-(4*i+3));
      return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}

function unformatCurrency(strValue)
{
  strValue = strValue.replace("$","").replace(",","");
  return parseFloat(strValue);
}
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now