0

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.

Ralph
  • 3
  • 1
  • 2
    Why not use the built-in flexible [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat)? – kelsny Aug 31 '22 at 15:42
  • 1
    Does this answer your question? [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – James Aug 31 '22 at 16:11
  • You are also continually formatting and deformatting the number because you are using the inner text as both data storage and display. separate the data from the display. keep the newly calculated value as an unformatted `data-` attribute and then place the formatted version in the innertext. – fnostro Aug 31 '22 at 18:08

1 Answers1

0

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>
fnostro
  • 4,531
  • 1
  • 15
  • 23
  • thank you for your explanation about the separation of data and formatting. I will definitely keep that in mind. And the code works perfectly. Thanks for your help! – Ralph Aug 31 '22 at 21:58