Get the last three digits of an integer

I want to change an integer such as 23457689 - 689, 12457245 - 245, etc.

I do not require rounding numbers and do not want to convert to String.

Any ideas on how this can be done in Python 2.7?

+6
source share
2 answers

Use the % operation:

 >>> x = 23457689 >>> x % 1000 689 

% is a mod operation (i.e. modulo ).

+20
source

Handle positive and negative integers correctly:

 >>> x = -23457689 >>> print abs(x) % 1000 689 

As a function in which you can select the number of leading digits:

 import math def extract_digits(integer, digits=3, keep_sign=False): sign = 1 if not keep_sign else int(math.copysign(1, integer)) return abs(integer) % (10**digits) * sign 

The restriction to avoid converting to str too pedantic. Converting to str would be a good way to do this if the format of the number can change or the format of the digits to be saved is changed.

 >>> int(str(x)[-3:]) ^^^^^ Easier to modify this than shoe-horning the mod function. 
+9
source

Source: https://habr.com/ru/post/982633/


All Articles