DextrousDave
DextrousDave

Reputation: 6793

Adding digit spacing with jQuery

I would like to inspect a span element and check for its number format and apply digit grouping to it with jquery

It the number has more than 3 digits, that is for >1000, it must do digit grouping, to separate the thousands from the hundreds, and the hundred thousands from the thousands:

eg.

<span>5500000.00</span>

should become

<span>5 500 000.00</span>

Is that possible with jQuery?

Upvotes: 2

Views: 2711

Answers (2)

dfsq
dfsq

Reputation: 193261

There are number of formatting plugins for this task. Or use can use regular expression.

function formatPrice(price) {
    return price.reverse().replace(/((?:\d{2})\d)/g, '$1 ').reverse();
}

// Need to extend String prototype for convinience
String.prototype.reverse = function() {
    return this.split('').reverse().join('');
}

Tests:

formatPrice('1234.00')   // "1 234.00"
formatPrice('12345.00')  // "12 345.00"
formatPrice('123456.00') // "123 456.00"

Maybe there is a way to do this without reverting a string?

Upvotes: 3

Related Questions