Reputation: 4022
What's the best way to get the Nth digit of a number in javascript?
For example, for 31415926
, the function will return 1 if N=2
.
EDIT: And if possible, tu return directly a number, not a string.
EDIT 2: It is from left to right.
Upvotes: 1
Views: 3669
Reputation: 3434
Personally, I would use:
function getNthDigit(number, n){
return parseInt((""+number).charAt(n));
}
But if you don't want it to be in String form ever you could use:
function getNthDigit(number, n){
var num = number,
digits = 0;
do{
num /= 10;
digits++;
}while(num>=1);
num = number / Math.pow(10, (digits - n));
num -= num % 1;
return (num % 10);
}
On second thought, just use the first option.
Upvotes: 2
Reputation: 3171
UPDATE: I didn't consider the fact that it was counting from the right. My bad!
Anyway, considering that the input is STILL a string, I'd use the same function, just with a little tweak.
Why don't you use the CharAt function? I think is the best option, considering the risk of multi-byte strings!!!
EDIT: I forgot the example:
var str = "1234567";
var n = str.charAt(str.length-2); // n is "6"
Upvotes: 0
Reputation: 8315
Try with that : (''+number)[nth]
or (''+number)[nth-1]
if one-based.
Upvotes: 3