Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last digits from an int

Tags:

javascript

Can't seem to find a good answer to this question. How do I remove the last 11 digits from an int?

The id could be one or more numbers in the beginning but there will always be 11 digits following the id. There will always be an id in the beginning. {id}{11 digits}.

var getId = function (digits) {
   // Do some stuff and return id
}

getId(110000000001); // Should return 1
getId(1110000000001); // Should return 11
getId(2010000000001); // Should return 20
like image 620
Niklas Avatar asked Nov 21 '13 14:11

Niklas


People also ask

How do you remove the last digit of an int in C++?

To remove the last digit just divide the nubmer by 10 and take the whole part ( floor(x / 10) ) as you planned originally.

How do you remove the last digit of an integer in Java?

substring()" is used to remove the last digit of a number.

How do you take the last two digits of an integer in Python?

Use the modulo operator to get the last 2 digits of a number, e.g. last_two = number % 100 . The modulo operator will return the last 2 digits of the number by calculating the remainder of dividing the number by 100.


1 Answers

Divide by 1e11 and take the floor:

var stripped = Math.floor(id / 1e11);

This avoids conversion to/from a string representation.

Note that the nature of JavaScript numerics is such that your "raw" values (the values with the 11 useless digits) can't have more than 5 digits in addition to those 11 before you'll start running into precision problems. I guess if you never care about the low-order 11 digits that might not be a problem.

like image 84
Pointy Avatar answered Sep 17 '22 13:09

Pointy