Format field to currency

Looking to format a field to US dollar currency style?  This function will round your value to the nearest tenth position, and add a dollar sign.

The following code is a JavaScript function. Simply pass your numeric value to this function and it will format it for you:

<script language="javascript">

function currency( num )
{
   var prefix = "$";
   var suffix = "";
   if ( num < 0 )
   {
       prefix = "($";
       suffix = ")";
       num = - num;
   }
       var temp = Math.round( num * 100.0 ); // convert to pennies!
       if ( temp < 10 ) return prefix + "0.0" + temp + suffix;
       if ( temp < 100 ) return prefix + "0." + temp + suffix;
       temp = prefix + temp; // convert to string!
       return temp.substring(0,temp.length-2) + "." + temp.substring(temp.length-2) + suffix;
}
</script>

You might also like...

Comments

Super Tal Always working hard!!

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Debugging is anticipated with distaste, performed with reluctance, and bragged about forever.” - Dan Kaminsky