get the number of n digit in a 2+ digit number

Anonymous picture Anonymous · Dec 24, 2010 · Viewed 12.2k times · Source

For example, getting "5" in "256". The closest I've gotten is Math.floor(256/10)), but that'll still return the numbers in front. Is there any simple way to get what I want or would I have to make a big function for it? Also, for clarity: "n digit" would be defined. Example, getDigit(2,256) would return 5 (second digit)

Answer

kemiller2002 picture kemiller2002 · Dec 24, 2010

how about

(12345 + "")[3] 

or

(12345 + "").charAt(3)

to count from the other end

[length of string - digit you want] so if you want the 2 it's:

5 - 4 = 1 
(12345 + "")[1] = "2"


function getNumber (var num, var pos){
  var sNum = num + "";

  if(pos > sNum.length || pos <= 0){return "";}

  return sNum[sNum.length - pos]; 

}