Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Get the second digit from a number?

I have a number assigned to a variable, like that:

var myVar = 1234;

Now I want to get the second digit (2 in this case) from that number without converting it to a string first. Is that possible?

like image 690
user1856596 Avatar asked Dec 19 '12 15:12

user1856596


People also ask

How do you find the second digit of a number?

You can do it by dividing by ten and then taking the remainder of division by ten: int second = (number / 10) % 10; In general, you could think of integer-dividing by a k -th power of ten as of dropping k least significant digits.

How do you find the first digit of a number?

To finding first digit of a number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10.

How do I find the first digit of a string?

To get the first number in a string:Use the search() method to get the index of the first number in the string. The search method takes a regular expression and returns the index of the first match in the string. Access the string at the index, using bracket notation.


2 Answers

So you want to get the second digit from the decimal writing of a number.

The simplest and most logical solution is to convert it to a string :

var digit = (''+myVar)[1]; 

or

var digit = myVar.toString()[1]; 

If you don't want to do it the easy way, or if you want a more efficient solution, you can do that :

var l = Math.pow(10, Math.floor(Math.log(myVar)/Math.log(10))-1); var b = Math.floor(myVar/l); var digit = b-Math.floor(b/10)*10; 

Demonstration

For people interested in performances, I made a jsperf. For random numbers using the log as I do is by far the fastest solution.

like image 188
Denys Séguret Avatar answered Sep 20 '22 02:09

Denys Séguret


1st digit of number from right → number % 10 = Math.floor((number / 1) % 10)

1234 % 10; // 4
Math.floor((1234 / 1) % 10); // 4

2nd digit of number from right → Math.floor((number / 10) % 10)

Math.floor((1234 / 10) % 10); // 3

3rd digit of number from right → Math.floor((number / 100) % 10)

Math.floor((1234 / 100) % 10); // 2

nth digit of number from right → Math.floor((number / 10^n-1) % 10)

function getDigit(number, n) {
  return Math.floor((number / Math.pow(10, n - 1)) % 10);
}

number of digits in a number → Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1 Credit to: https://stackoverflow.com/a/28203456/6917157

function getDigitCount(number) {
  return Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1;
}

nth digit of number from left or right

function getDigit(number, n, fromLeft) {
  const location = fromLeft ? getDigitCount(number) + 1 - n : n;
  return Math.floor((number / Math.pow(10, location - 1)) % 10);
}
like image 38
Gerges Beshay Avatar answered Sep 21 '22 02:09

Gerges Beshay