0

I'm new at javascript and trying to do some loop that will automaticly will format a number (1000 = 1K , 10000 = 10k 100000 = 100k )

formatting to 1K works and then it stops for some reason...

for me this loop makes sense :

loop will cycle once so the condition will be true , this will give me the first 2 integers and a 'K', after that the loop will break

if condition is not true , loop should be continue...

this is probaly not the ideal way to do it , but i wondering why my logic thinking is wrong

thanks advanced and sorry for my bad english.

<body >
 <p>Number: <span id="number"></span></p>

 <script>
  len=1;
  thousand=1000;
  million =1000000;
  num= 10001;
  for(thousand;thousand<million;thousand*=10){ //when thousand is less then a million , multiply thousand times 10
   if(num>=thousand && num<(thousand*10)){ // should cycle the loop twice so i got num>=10000 && num<100000 
    document.getElementById("number").innerHTML = num.toString().substring(0,len)+" K";
    len+=1; // increase by 1 , so i will get  10 K instead of 1 K  
    break; // should break now since condition is true after second cycle 
   }   
  }
  // probaly not the ideal method to do this , i just want to know my problem because this loop makes sense to me....
 </script> 
</body>
nudago
  • 13
  • 1

1 Answers1

0

A loop just makes no sense in this case, because you don't have an array type to iterate over. Additionally generating a range to loop, like you are tyring to do isn't worth, since you could just

n = Math.floor(n / 1000) + 'k';

see chrisz answer for a working 'number to k' filter.

If you really want to loop. Try this:

let n = 3024;
for (let i = 0; i < 1000; i++) {
  if (n >= i * 1000 && n < (i + 1) * 1000) {
    console.log(i + 'k');
    break;
  }
}
Armin Bu
  • 1,330
  • 9
  • 17