Thursday, October 4, 2007

Adding commas and Removing commas to represent US format

Tutorial Link-1

Tutorial Link-2

// This function formats numbers by adding commas

function addCommas() {

var nStr = document.forms[0].requestAmount.value;
alert("Amount: " + nStr);
var prefix = '$' '';
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + ',' + '$2');
alert("Result: " + (prefix + x1 + x2));
document.forms[0].requestAmount.value = (prefix + x1 + x2);
alert("Final Request Amount: " + document.forms[0].requestAmount.value);
}

// This function formats numbers by removing commas

function removeCommas() {

// alert("inputvalue: " + document.forms[0].requestAmount.value);
var StartNumber = document.forms[0].requestAmount.value;
var TempNumber = StartNumber.replace(/\,/g,'');
var ReplacedNumber = TempNumber.replace(/\$/,'');
document.forms[0].requestAmount.value = ReplacedNumber;
// alert("Result: " + document.forms[0].requestAmount.value);

}

Tutorial on replace function.

No comments: