Format Input field like $ simbol and decimals

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
RIGOLETO
Forum Commoner
Posts: 37
Joined: Fri Nov 20, 2009 10:13 am

Format Input field like $ simbol and decimals

Post 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
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Format Input field like $ simbol and decimals

Post 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
Post Reply