2

I am currently creating a number counter (from 0 to a value) and I am having some trouble with getting the number to render if it's separated by a comma.

I have found some potential fixes such as toLocaleString but I can't get it to work - could anyone point me in the right direction?

Currently when I use 130,000 it returns NaN.

Thanks!

$('.panel-text-style-c').each(function() {

  $(this).prop('Counter', 0).animate({
    Counter: $(this).text()
  }, {
    duration: 2000,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now).toString());
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='panel-text-style-c'>130,000</span>

The following above

Pedram
  • 15,766
  • 10
  • 44
  • 73
Mark
  • 81
  • 8

2 Answers2

4

In JS, a , is not valid for use in a value to be parsed to an integer. This is why you receive the NaN output.

To fix this use replace() to remove the comma before providing it to the Counter property:

$('.panel-text-style-c').each(function() {
  $(this).prop('Counter', 0).animate({
    Counter: $(this).text().replace(/,/g, '')
  }, {
    duration: 2000,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now).toLocaleString());
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='panel-text-style-c'>130,000</span>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • After implementing this, the comma doesn't get added in again, is this possible? – Mark May 29 '18 at 10:17
  • You could use `toLocaleString()` in the display logic. I've updated the answer to show you how. Note that if you want to force the comma grouping regardless of locale, use [this](https://stackoverflow.com/questions/1990512/add-comma-to-numbers-every-three-digits) – Rory McCrossan May 29 '18 at 10:18
  • Works a treat, thank you very much buddy!!! Will mark as the correct answer once it allows me to! – Mark May 29 '18 at 10:19
  • No problem, glad to help – Rory McCrossan May 29 '18 at 10:25
0

Try this code:

$('.panel-text-style-c').each(function() {
  var num =   $(this).text().replace(',', '');
  
  $(this).prop('Counter', 0).animate({
    Counter: num
  }, {
    duration: 2000,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now).toString());
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='panel-text-style-c'>130,000</span>
Sahil Sharma
  • 1,813
  • 1
  • 16
  • 37