Softey
Softey

Reputation: 1491

Truncating a int

Evening all,

I am curious as how you would "cut" an integer down. For example:

num = 12345678 
num_shrunk = "for example 3"(num)
print(num_shrunk)
123

I am aware of the round function however I need to be precise. I have tried format(num, "3d") however that is for decimal places. I also can't say only print num[0:3] as it isn't an integer.

Is there a simple way here of doing this that I am clearly not seeing?

Upvotes: 0

Views: 1088

Answers (3)

user2913685
user2913685

Reputation: 71

def shrink(number,amount=0): return number//(10**amount)
print shrink(1234,2)

should work as intended. d//i is floor division and d**i is power multiplication. not giving an amount (shrink(5)) will return 5.

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 114108

N=3
int(str(num)[:N])

should do it ...

you could also do it mathematically

def nDigits(int_n):
    return nDigits(int_n//10) + 1 if int_n > 10 else 1
num//(10*(nDigits(num)-N)
# nDigits can also be caluclated as follows: numDigits = int(math.log(num,10))+1

although since you still need to convert it to a string to get the total number of digits

Upvotes: 1

Sledge
Sledge

Reputation: 1345

I can think of one way to accomplish this in R by using modulus division:

> num <- 12345678
> numshrunk <- (num - num %% 100000) / 100000
> numshrunk
123

You can apply the same technique in python substituting the "<-" and "%%" for the appropriate variable assignment and modulus division operators respectively.

A more useful version of above:

> N = 3
> num <- 12345678
> numshrunk <- (num - num %% 10^(N-1)) / 10^(N-1)
> numshrunk
123

Upvotes: 0

Related Questions