Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  96] [ 1]  / answers: 1 / hits: 113159  / 12 Years ago, wed, december 19, 2012, 12:00:00

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?


More From » numbers

 Answers
7

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.


[#81324] Tuesday, December 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dustin

Total Points: 599
Total Questions: 105
Total Answers: 106

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
dustin questions
;