Junky
Junky

Reputation: 1026

jQuery Counter - Whole Numbers or Decimals

I am using this jQuery script to display a counter. I need to show both whole numbers and decimals but I can't seem to determine which is which.

jQuery('.counter-wrap .count').each(function() {

  jQuery(this).prop('Counter', 0).animate({
    Counter: jQuery(this).attr('data-count')
  }, {
    duration: 1000,
    easing: 'swing',
    step: function(now) {
      jQuery(this).text(
        Math.round(this.Counter, 0) == this.Counter ?
        this.Counter :
        this.Counter.toFixed(1));
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="counter-wrap">
  <h2><span class="count" data-count="6.8">0</span>M</h2>
</div>

<div class="counter-wrap">
  <h2><span class="count" data-count="5.2">0</span>M</h2>
</div>

<div class="counter-wrap">
  <h2><span class="count" data-count="90">0</span></h2>
</div>

Please check my fiddle

Upvotes: 2

Views: 268

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

To only round to a decimal place when one is included in the original value you need to interrogate that value, not the Counter property, to see if it had a floating point.

Also note the use of the data() method in the example in order to avoid the need to coerce any data types:

jQuery($ => {
  $('.counter-wrap .count').each(function() {
    $(this).prop('Counter', 0).animate({
      Counter: $(this).data('count')
    }, {
      duration: 1000,
      easing: 'swing',
      step: function(now) {
        $(this).text(this.Counter.toFixed($(this).data('count') % 1 === 0 ? 0 : 1));
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="counter-wrap">
  <h2><span class="count" data-count="6.8">0</span>M</h2>
</div>

<div class="counter-wrap">
  <h2><span class="count" data-count="5.2">0</span>M</h2>
</div>

<div class="counter-wrap">
  <h2><span class="count" data-count="90">0</span></h2>
</div>

Upvotes: 3

Related Questions