JQuery Number Formatting

Eran Medan picture Eran Medan · Sep 7, 2011 · Viewed 319.6k times · Source

There are way too many questions and answers about this basic functionality, I cannot see the wood for the trees.

In Java there is only one simple answer (java.text.NumberFormat and its subclasses) so I'm sure the majority of plugins, questions and answers will mature eventually to a de-facto standard for JQuery.

This plugin is the best I found so far, but I don't know if it's still developed, is mature etc.

http://plugins.jquery.com/project/numberformatter

Is there a better solution? Is it mature / active enough to rely on?


Edit:

I would like to be able to format currencies, decimal, integers based on the same format patterns Java uses, so that data recieved on the client side can be formatted without sending it first to the server.

e.g.

Format 1000 to $1,000 or 1,000.00 etc (locale support is nice)

Seems that http://plugins.jquery.com/project/numberformatter does the job but the question was: "Am I using the right thing?" or "Is there a better way to do so?"

Answer

Abe Miessler picture Abe Miessler · Sep 7, 2011

I would recommend looking at this article on how to use javascript to handle basic formatting:

function addCommas(nStr)
{
    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');
    }
    return x1 + x2;
}

source: http://www.mredkj.com/javascript/numberFormat.html

While jQuery can make your life easier in a million different ways I would say it's overkill for this. Keep in mind that jQuery can be fairly large and your user's browser needs to download it when you use it on a page.

When ever using jQuery you should step back and ask if it contributes enough to justify the extra overhead of downloading the library.

If you need some sort of advanced formatting (like the localization stuff in the plugin you linked), or you are already including jQuery it might be worth looking at a jQuery plugin.

Side note - check this out if you want to get a chuckle about the over use of jQuery.