Easy currency formatting with javascript

May 16, 2008

Sometimes you need HTML text fields to format currencies with a fixed number of decimal digits. One thing that isn’t very known, and sorry if it actually is for anyone, but javascript already arrive with a function that do exactly the job for us.

function formatToCurrency(el){
var value = el.value;
el.value = new Number(value).toFixed(2);
}

Then you could trigger this function as the onblur event of your form control this way:


onblur="formatToCurrency(this)"

That’s it, now when you move out your mouse from the control it will automatic format your input.

I know this code is really poor but it satisfy the needs of a lot of users. The code isn’t localized but it isn’t hard to figure out how to do it. Actually what brought me to the toFixed function was my searches on a localized generic number formatting script.

Leave a comment