Currency Formatter

[Total: 0    Average: 0/5]

This script accepts a number or string and formats it like U.S. currency.

Head Code:

<script>
function formatCurrency( num ) {
        var isNegative = false;
        num = num.toString().replace(/\$|\,/g,'');
        if( isNaN( num ) ) {
          num = "0";
        }
        if ( num < 0 ) {
          num = Math.abs( num );
          isNegative = true;
        }
        cents = Math.floor( ( num * 100 + 0.5 ) % 100 );
        num = Math.floor( ( num * 100 + 0.5 ) / 100 ).toString();
        if ( cents < 10 ) {
          cents = "0" + cents;
        }
        for ( 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 ) );
        }

        var result = '$' + num + '.' + cents;
        if ( isNegative ) {
          result = "-" + result;
        }
        return result;
      }
</script>

Body Code:

<center>
<form name=currencyform>
Enter a number then click the button: <input type=text name=input size=10 value="1000434.23">
<input type=button value="Convert" onclick="this.form.input.value=formatCurrency(this.form.input.value);">
<br><br>
or enter a number and click another field: <input type=text name=input2 size=10 value="1000434.23" onBlur="this.value=formatCurrency(this.value);">
</form>
</center>

Times Viewed: 0

Leave a Reply

Your email address will not be published. Required fields are marked *