user1856596 - 1 month ago 4x

Javascript Question

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?

Answer

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

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

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

or

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

If you don't want to do it the easy way, 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;
```

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

Source (Stackoverflow)

Comments