Niklas
Niklas

Reputation: 13135

Remove last digits from an int

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

Upvotes: 9

Views: 21910

Answers (6)

Joke_Sense10
Joke_Sense10

Reputation: 5402

Try this:

var str = 1100000000011; 
var res = str.toString().substr(0, str.toString().length - 11);

Demo

Upvotes: 6

Shawn G.
Shawn G.

Reputation: 622

You can convert the number to a string and slice the last 11 characters from the end

parseInt( digits.toString().slice(0, -11) );

Using .slice( 0 , [ negative_number ]); will slice x characters from the end of the string

More information on .slice() Here

Upvotes: 1

MKII
MKII

Reputation: 911

You can use division and 10^11 to do so. Edit: my bad

Upvotes: 2

Artem Sobolev
Artem Sobolev

Reputation: 6069

You can convert your number to string and delete tailing digits:

digits.toString().replace(/\d{11}$/, '')

By the way, you better don't use ints (or to be precise, Numbers) because if number is greater than 2147483648 (by absolute value), it'll be represented internally as double resulting in precision loss. If don't need tailing digits, then it's okay — use division approach suggested in other answers (this one could break because of scientific notation). But if you want to keep all the data, you should represent your numbers with strings.

Upvotes: 3

Pointy
Pointy

Reputation: 413712

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.

Upvotes: 13

Max Novich
Max Novich

Reputation: 1169

var getId = function (digits) {
   var id = parseInt((digits/(1e11)),0);
}

Upvotes: 1

Related Questions