johfarrar
01-07-2003, 02:46 PM
I was wondering if anyone can tell me how to get javascript to format numbers it creates.
I have a few variables that are added and rounded. It prints the right number out, but I need it to have commas ... ie $1,000.
Please help.
beetle
01-07-2003, 04:28 PM
Here's a currency method I wrote. Works for both Numbers and Strings. A couple examples are included.
<script type="text/javascript">
String.prototype.currency = function( grouping, dollar, round )
{
var point = this.indexOf( "." );
var anynum = parseFloat( this );
var result = ( round ) ? Math.round( anynum * 100 ) / 100 : Math.floor( anynum * 100 ) / 100;
result = result.toString(10);
if (point == -1)
result = parseInt(anynum) + ".00";
else
{
var decimals = result.substring( point + 1 );
if ( decimals.length == 1 ) result = result + "0";
}
if ( grouping )
{
point = result.indexOf( "." );
var dollars = result.substring( 0, point );
var cents = result.substring( point );
var commas = parseInt( dollars.length / 3 );
var temp = new Array();
for ( var i = commas; i>=0; i-- )
{
if ( dollars.length > 3 )
{
temp[i] = dollars.substring( dollars.length-3 );
dollars = dollars.substring( 0, dollars.length-3 );
}
else
{
temp[i] = dollars;
}
}
dollars = temp.join( "," );
result = dollars + cents;
}
return ( dollar ) ? "$ " + result : result;
}
Number.prototype.currency = function( g, d, r )
{
// g == grouping, d == dollar sign, r == round
return this.toString(10).currency( g, d, r );
}
var num = 12345.789;
alert( num.currency( 1, 1, 1 ) );
num = "5.555";
alert( num.currency( 1, 1, 0 ) );
num = 702658230;
alert( num.currency( 1, 0, 0 ) );
</script>
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.