# Getting x digits from the start or end of a number?

#### Apple30

Hi everyone, does any one know how one could get x digits from either the left or right side of a number?

For example, if the number is 12345 then 2 digits from the left would be 12, and from the right would be 45.

I know that this can be easily solved if the number is converted to a string of characters and then converted back into a number, but I was curious if there is an efficient mathematical way to solve this?
Perhaps using functions like min, max, floor, pow, sqrt, etc.?

Thanks.

#### Maschke

Hi everyone, does any one know how one could get x digits from either the left or right side of a number?

For example, if the number is 12345 then 2 digits from the left would be 12, and from the right would be 45.

I know that this can be easily solved if the number is converted to a string of characters and then converted back into a number, but I was curious if there is an efficient mathematical way to solve this?
Perhaps using functions like min, max, floor, pow, sqrt, etc.?

Thanks.
Let $\%$ be the mod operator, so $n \% m$ is the remainder when $n$ is divided by $m$.

If $x$ is your number, then $x \% 10$ is the rightmost digit and $(x - x \% 10) / 10$ is the leftmost everything else. That is, $12345 \% 10 = 5$, and $(12345 - 5) / 10 = 1234$. Likewise $x \% 100$ gives the rightmost two digits and $(x - x \% 100) / 100$ is everything to the left of the two rightmost digits. Etc.

Last edited:

#### romsek

Math Team
mathematically this is simple enough

$\text{last$n$digits of number$M$} = M \pmod {10^n}$

To get the leading digits you need to know how many digits there are.

$d = \left \lfloor \log_{10}(M)\right\rfloor + 1$

$\text{first$n$digits of number M} = \left \lfloor \dfrac{M}{10^{d-n}}\right\rfloor$

Now the issue is that if $M$ gets to be any significant size many systems won't be able to handle taking logs or floors or what have you.
In that case you'll either have some special data type that's able to hold arbitrarily large (to a point) numbers and you'll have to code up your own functions to deal with that data type.
Or you'll be given a list of digits, in which case finding the first and last $n$ of them is trivial.

topsquark

#### Yooklid

Same as the previous two replies, but using standard spreadsheet functions:
To get the leftmost n digits of number x:
INT(x/10^INT(LOG(x)+1-n))

To get the rightmost n digits of number x:
MOD(x,10^n)

romsek

#### Apple30

Thanks everyone, works great.

However, I did run into problems when the number was negative. Is there a way to modify the spreadsheet formula so that if the number is -12345 it will return -12 or -45?

#### romsek

Math Team
feed the above formulas ABS(x) and multiply the result by SiGN(x) where x is the big number in question

topsquark

Thanks!!