Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - JQuery Number Formatting

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?"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...