Click to See Complete Forum and Search --> : Putting commas in every three numbers


florida
06-06-2003, 02:20 PM
I have dollar output but need to put a comma for the every three numbers.
For example:
$220469.06 Should be $220,469.06

And this:
$2469.06 should be $2,469.06

and this:
$234.03 should stay $234.03

And this:
$2324566.00 should be $2,324,566.00

My attempt isnt working:


number = form1.dollarTotal.value;
newDollarTotal = number.subtring(0,3)+","+number.subtring(4,6);

Charles
06-06-2003, 03:16 PM
Put the following in the document's head.

<script type="text/javascript">
<!--
String.prototype.reverse = function () {return this.split('').reverse().join('')};

function Dollars (d) {if (isNaN(d)) {this.num = Number(d.replace(/[$,]/g, ''))} else {this.num = d}};

Dollars.prototype.valueOf = function () {return this.num};

Dollars.prototype.toString = function () {
var s = this.num < 0 ? '-' : '';
var l = Math.floor(Math.abs(this.num)).toString();
var r = Math.round((Math.abs(this.num) % 1) * 100).toString();
if (l.length > 4) l = l.reverse().match(/\d{1,3}/g).join(',').reverse();
if (r < 10) r = '0' + r;
return '$' + s + [l,r].join('.');
}
// -->
</script>

Then you can create Dollars objects that will behave like numbers when you use them like numbers but will look like US Currency when you use them like strings.

<input type="text" onchange="this.value = new Dollars(this.value)">

<input type="text" onchange="this.value = new Dollars(new Dollars(this.value) * 10)">