JQuery Number Formatting

前端 未结 8 912
鱼传尺愫
鱼传尺愫 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条回答
  •  -上瘾入骨i
    2020-11-27 16:15

    I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. Could be usefull.

    number_format = function (number, decimals, dec_point, thousands_sep) {
            number = number.toFixed(decimals);
    
            var nstr = number.toString();
            nstr += '';
            x = nstr.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? dec_point + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
    
            while (rgx.test(x1))
                x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');
    
            return x1 + x2;
        }
    

    For example:

    var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56
    

提交回复
热议问题