JQuery Number Formatting

前端 未结 8 932
鱼传尺愫
鱼传尺愫 2020-11-27 15:43

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 (jav

8条回答
  •  隐瞒了意图╮
    2020-11-27 16:15

    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.

提交回复
热议问题