javascriptjqueryseparatordigit-separator

how to separate number using javascript?


I have a quetion please help me. I have number 21 or 22 or 23 etc. and I want to separate that number to be 20 and 1 or 20 and 2 or 20 and 3 etc. how to make it programmaticly in javascript. Sorry before cause I really confused and dont know the keyword to search on internet. Thanks guys hope U all can help me


Solution

  • Since your numbers are 2 digits max you can try this approach. First divide the number by 10 then for example if we divide 21 by 10 we get 2 and some reminder with math.floor we get rid of the reminder just 2 is left then we multiply 2 by 10 we get 20 that is the first part. The second part just use % on the the number to get the reminder so for example 21 % 10 it would be 1

    var numbers = [20, 21, 22];
    var numberSeperator = function(number){
      return [Math.floor(number / 10) * 10, number % 10];
    }
    
    for(var i = 0; i < numbers.length; i++){
      console.log(numberSeperator(numbers[i]))
    }