Page 1 of 1

Format Input field like $ simbol and decimals

Posted: Thu Jan 07, 2010 2:56 pm
by RIGOLETO
Hi there,

I need a sample of jave script to format a numeric input field, just I need to show the $ simmbol and the field should put two decila by defaul, just like this sample

$1,200.23

Thanks

Re: Format Input field like $ simbol and decimals

Posted: Fri Jan 08, 2010 11:57 am
by kaszu
I feel generous today, so I will write it for you

Code: Select all

function formatCurrency(x) {
    var y = ~~((~~x).toString().length/3);
    var str = x.toFixed(2);
    while(y--) str=str.replace(/(\d)(\d{3})(,|\.)/, "$1,$2$3");
    return str;
}
How it works:

Code: Select all

> var y = ~~((~~x).toString().length/3);
~~number is the same as Math.floor(number), only a little faster
what this piece of code does is calculates at least how many times we need need to insert comma in the string (how many groups by 3 digits exist before dot)
this is how many times we will need to insert comma
 
> var str = x.toFixed(2);
get string with 2 decimals after dot, "1234.5" => "1234.50"   "12" => "12.00"   "12.345" => "12.35"
 
> while(y--) str=str.replace(/(\d)(\d{3})(,|\.)/, "$1,$2$3");
replace 4 digits in a row which are followed by comma or dot with "1st digit from original string" "comma" "next 3 digits from original string" "comma or dot from original string"
I hope it makes sense. Don't forget to say Thank You if you will use this code