Let’s say I have an arbitrary integer 874,623,123 how do I round it down to 800,000,000 and up to 900,000,000? Another example is 759 round up to 800 or down to 700. The size of the integer is unknown.
Is there a built-in method to do it? If not, what’s the best way to work it out? Sorry not a math expert here.
EDIT: So far I have looked at
Rounding down integers to nearest multiple
Python round up integer to next hundred
Both use a predefined divider
Advertisement
Answer
You can use the math
module:
import math n = 874623123 # c contains the same number of digits as n c = 10 ** int(math.log10(n)) print(math.floor(n/c) * c) # 800000000 print(math.ceil(n/c) * c) # 900000000