add commas to a number in jQuery

2019-01-03 13:06发布

I have these numbers

10999 and 8094 and 456

And all i want to do is add a comma in the right place if it needs it so it looks like this

10,999 and 8,094 and 456

These are all within a p tag like this <p class="points">10999</p> etc.

Can it be done?

I've attempted it here with the help of other posts http://jsfiddle.net/pdWTU/1/ but can't seem to get it to work

Thanks

Jamie

UPDATE

Messed around a bit and managed to figure it out here http://jsfiddle.net/W5jwY/1/

Going to look at the new Globalization plugin for a better way of doing it

Thanks

Jamie

11条回答
趁早两清
2楼-- · 2019-01-03 13:35

Take a look at recently released Globalization plugin to jQuery by Microsoft

查看更多
祖国的老花朵
3楼-- · 2019-01-03 13:37

Here is my coffeescript version of @baacke's fiddle provided in a comment to @Timothy Perez

class Helpers
    @intComma: (number) ->
        # remove any existing commas
        comma = /,/g
        val = number.toString().replace comma, ''

        # separate the decimals
        valSplit = val.split '.'

        integer = valSplit[0].toString()
        expression = /(\d+)(\d{3})/
        while expression.test(integer)
            withComma = "$1,$2"
            integer = integer.toString().replace expression, withComma

        # recombine with decimals if any
        val = integer
        if valSplit.length == 2
            val = "#{val}.#{valSplit[1]}"

        return val
查看更多
相关推荐>>
4楼-- · 2019-01-03 13:44

Using toLocaleString ref at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

function formatComma(value, sep = 0) {
      return Number(value).toLocaleString("ja-JP", { style: "currency", currency: "JPY", minimumFractionDigits: sep });
    }
console.log(formatComma(123456789, 2)); // ¥123,456,789.00
console.log(formatComma(123456789, 0)); // ¥123,456,789
console.log(formatComma(1234, 0)); // ¥1,234

查看更多
够拽才男人
5楼-- · 2019-01-03 13:47
    function delimitNumbers(str) {
      return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
        return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
      });
    }

    alert(delimitNumbers(1234567890));
查看更多
爷的心禁止访问
6楼-- · 2019-01-03 13:48

I'm guessing that you're doing some sort of localization, so have a look at this script.

查看更多
登录 后发表回答