1

What's the best way to format all the numbers on a web page with the span class? using jquery?

<span class="number">100065</span>
<span class="number">9896</span>
<span class="number">3946</span>
<span class="number">9606</span>

Result 100k 9.8k 3.9k 9.6k

sierra.charli3
  • 205
  • 2
  • 22
  • Possible duplicate of [How to format a number as 2.5K if a thousand or more, otherwise 900 in javascript?](https://stackoverflow.com/questions/9461621/how-to-format-a-number-as-2-5k-if-a-thousand-or-more-otherwise-900-in-javascrip) – kwoxer Aug 29 '18 at 13:20

1 Answers1

1

It's kind of a duplicate but here is the proper solution for you special case:

String.prototype.endsWith = function(suf) {
    return (this.indexOf(suf, this.length - suf.length) !== -1) ? this.slice(0, -2) : this;
};
function kF(num) { 
  return num > 999 ? 
    (num/1000).toString().slice(0, - 2).endsWith('.0') + 'k' : 
    num 
}
jQuery('span.number').text(function(i, oldText) { return kF(oldText); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="number">100065</span>
<span class="number">9896</span>
<span class="number">3946</span>
<span class="number">9606</span>
<p>Some more...</p>
<span class="number">100065568</span>
<span class="number">20054065568</span>

Latest version now also fixes the issue with 100.0k.

kwoxer
  • 3,734
  • 4
  • 40
  • 70
  • `str.replace(".0", "")` This would be even better and faster, but does not check if it's on the right side. Check if this might be also a proper solution for you. – kwoxer Aug 30 '18 at 09:54