Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python trim number without converting to string first

Tags:

python

if i have an integer like this:

123456789

I would like to return only 12345 - so trimming the number to a length of 5 digits.

Is this possible without first converting to a string? I cant see any built in function to do this.

like image 987
Marty Wallace Avatar asked Feb 26 '26 20:02

Marty Wallace


1 Answers

import math

def five_digits(number):
    ndigits = int(math.log10(number))+1
    try:
        return number//int(10**(ndigits-5))
    except ZeroDivisionError:
        return number

print five_digits(10000000)
print five_digits(12345678)
print five_digits(12345)
print five_digits(1234)  #don't know what you want to do with this one...
like image 74
mgilson Avatar answered Mar 01 '26 08:03

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!