2

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?

Sid
  • 4,893
  • 14
  • 55
  • 110
DextrousDave
  • 6,603
  • 35
  • 91
  • 134

2 Answers2

3

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?

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • thank you very much. what would you suggest? I actually want to implement this on a knockout function (data is populated by knockout, but I cannot get it working...see fiddle here: http://jsfiddle.net/rRaHm/14/ - I can only do decimal placement, not digit grouping as well – DextrousDave Apr 17 '13 at 12:56
  • 1
    Glad you didn't include "123.00" on the test. To see the difference change the space with a comma for the delimiter, you'll find the result something like ",123.00". But then again as we can see the question is about a space not a comma. – John Smith Nov 14 '16 at 14:22
1

This links might help :

https://code.google.com/p/jquery-numberformatter/

Javascript: Easier way to format numbers?

Community
  • 1
  • 1
Sid
  • 4,893
  • 14
  • 55
  • 110