Search code examples
javascriptnumberscounting

JS counting numbers with thousands separator


For example, I want to display the number 90,000 while it is counting up.

I have already managed to count up with the following code, but without "." or ",":

<div class="fact">
<div class="number" num="90000">0</div>
</div>
const counters = document.querySelectorAll('.number');
            const speed = 500;
            
            counters.forEach( counter => {
               const animate = () => {
                  const value = +counter.getAttribute('num');
                  const data = +counter.innerText;
                 
                  const time = value / speed;
                 if(data < value) {
                      counter.innerText = Math.ceil(data + time);
                      setTimeout(animate, 1);
                    }else{
                      counter.innerText = value;
                    }
                 
               }
               
               animate();
            });

Have already found examples with thousands separator but I can't manage to convert it to my project.

while (/(\d+)(\d{3})/.test(val.toString())){
          val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');

I have little experience with javascript.


Solution

  • Per my comment, Keep data separate from formatting

    const counters = document.querySelectorAll('.number');
    const speed = 500;
    const formatter = new Intl.NumberFormat();
    
    counters.forEach(counter => {
      const animate = () => {
        let value = +counter.dataset.num;
        let data = +counter.dataset.state;
        let time = value / speed;
    
        if (data < value) {
          counter.dataset.state = Math.ceil(data + time);
          setTimeout(animate, 1);
        }
        counter.innerText = formatter.format(counter.dataset.state);
      }
      animate();
    });
    <div class="fact">
      <div class="number" data-num="90000" data-state="0">0</div>
      <div class="number" data-num="45000" data-state="0">0</div>
    </div>