Python Round Up Integer to Next Hundred

Python round up integer to next hundred

Rounding is typically done on floating point numbers, and here there are three basic functions you should know: round (rounds to the nearest integer), math.floor (always rounds down), and math.ceil (always rounds up).

You ask about integers and rounding up to hundreds, but we can still use math.ceil as long as your numbers smaller than 253. To use math.ceil, we just divide by 100 first, round up, and multiply with 100 afterwards:

>>> import math
>>> def roundup(x):
... return int(math.ceil(x / 100.0)) * 100
...
>>> roundup(100)
100
>>> roundup(101)
200

Dividing by 100 first and multiply with 100 afterwards "shifts" two decimal places to the right and left so that math.ceil works on the hundreds. You could use 10**n instead of 100 if you want to round to tens (n = 1), thousands (n = 3), etc.

An alternative way to do this is to avoid floating point numbers (they have limited precision) and instead use integers only. Integers have arbitrary precision in Python, so this lets you round numbers of any size. The rule for rounding is simple: find the remainder after division with 100, and add 100 minus this remainder if it's non-zero:

>>> def roundup(x):
... return x if x % 100 == 0 else x + 100 - x % 100

This works for numbers of any size:

>>> roundup(100)
100
>>> roundup(130)
200
>>> roundup(1234567891234567891)
1234567891234567900L

I did a mini-benchmark of the two solutions:

$ python -m timeit -s 'import math' -s 'x = 130' 'int(math.ceil(x/100.0)) * 100'
1000000 loops, best of 3: 0.364 usec per loop
$ python -m timeit -s 'x = 130' 'x if x % 100 == 0 else x + 100 - x % 100'
10000000 loops, best of 3: 0.162 usec per loop

The pure integer solution is faster by a factor of two compared to the math.ceil solution.

Thomas proposed an integer based solution that is identical to the one I have above, except that it uses a trick by multiplying Boolean values. It is interesting to see that there is no speed advantage of writing the code this way:

$ python -m timeit -s 'x = 130' 'x + 100*(x%100>0) - x%100'
10000000 loops, best of 3: 0.167 usec per loop

As a final remark, let me also note, that if you had wanted to round 101–149 to 100 and round 150–199 to 200, e.g., round to the nearest hundred, then the built-in round function can do that for you:

>>> int(round(130, -2))
100
>>> int(round(170, -2))
200

How can i round a number down to nearest hundred in python?

You may use either of these three ways (there may exist many more ways):

import math
print(math.floor(5398 / 100.00) * 100)

Output is 5300 as expected.

rounded = int(5398 / 100) * 100
print(rounded)

Still the output is 5300.

import numpy
print(int(numpy.floor(5398 / 100.0) * 100))

The output is still 5300 :)

Have Fun :)

How to round up to the next integer ending with 2 in Python?

import math
x = [10, 21, 22, 23, 34]

for n in x:
print((math.ceil((n-2)/10)*10)+2)

outputs:

12
22
22
32
42

How to round up/down an int in Python?

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

How do you round UP a number?

The math.ceil (ceiling) function returns the smallest integer higher or equal to x.

For Python 3:

import math
print(math.ceil(4.2))

For Python 2:

import math
print(int(math.ceil(4.2)))

Python round UP/DOWN integers in dictionary with list

Ceil and floor equivalent in Python 3 without Math module?

This should do like what you want.

round_degree = 100
number = 2151

# Example rounding down to nearest 100
rounded_down = (number // round_degree) * round_degree
print(number, rounded_down )

# Example rounding up to nearest 100
rounded_up = -(-number // round_degree) * round_degree
print(number, rounded_up)

Round number to nearest integer

TL;DR:

round(x)

will round it and change it to integer.

You are not assigning round(h) to any variable. When you call round(h), it returns the integer number but does nothing else; you have to change that line for:

h = round(h)

to assign the new value to h.


As @plowman said in the comments, Python's round() doesn't work as one would normally expect, and that's because the way the number is stored as a variable is usually not the way you see it on screen. There are lots of answers that explain this behavior.

One way to avoid this problem is to use the Decimal as stated by this answer.

In order for this answer to work properly without using extra libraries it would be convenient to use a custom rounding function. I came up with the following solution, that as far as I tested avoided all the storing issues. It is based on using the string representation, obtained with repr() (NOT str()!). It looks hacky but it was the only way I found to solve all the cases. It works with both Python2 and Python3.

def proper_round(num, dec=0):
num = str(num)[:str(num).index('.')+dec+2]
if num[-1]>='5':
return float(num[:-2-(not dec)]+str(int(num[-2-(not dec)])+1))
return float(num[:-1])

Tests:

>>> print(proper_round(1.0005,3))
1.001
>>> print(proper_round(2.0005,3))
2.001
>>> print(proper_round(3.0005,3))
3.001
>>> print(proper_round(4.0005,3))
4.001
>>> print(proper_round(5.0005,3))
5.001
>>> print(proper_round(1.005,2))
1.01
>>> print(proper_round(2.005,2))
2.01
>>> print(proper_round(3.005,2))
3.01
>>> print(proper_round(4.005,2))
4.01
>>> print(proper_round(5.005,2))
5.01
>>> print(proper_round(1.05,1))
1.1
>>> print(proper_round(2.05,1))
2.1
>>> print(proper_round(3.05,1))
3.1
>>> print(proper_round(4.05,1))
4.1
>>> print(proper_round(5.05,1))
5.1
>>> print(proper_round(1.5))
2.0
>>> print(proper_round(2.5))
3.0
>>> print(proper_round(3.5))
4.0
>>> print(proper_round(4.5))
5.0
>>> print(proper_round(5.5))
6.0
>>>
>>> print(proper_round(1.000499999999,3))
1.0
>>> print(proper_round(2.000499999999,3))
2.0
>>> print(proper_round(3.000499999999,3))
3.0
>>> print(proper_round(4.000499999999,3))
4.0
>>> print(proper_round(5.000499999999,3))
5.0
>>> print(proper_round(1.00499999999,2))
1.0
>>> print(proper_round(2.00499999999,2))
2.0
>>> print(proper_round(3.00499999999,2))
3.0
>>> print(proper_round(4.00499999999,2))
4.0
>>> print(proper_round(5.00499999999,2))
5.0
>>> print(proper_round(1.0499999999,1))
1.0
>>> print(proper_round(2.0499999999,1))
2.0
>>> print(proper_round(3.0499999999,1))
3.0
>>> print(proper_round(4.0499999999,1))
4.0
>>> print(proper_round(5.0499999999,1))
5.0
>>> print(proper_round(1.499999999))
1.0
>>> print(proper_round(2.499999999))
2.0
>>> print(proper_round(3.499999999))
3.0
>>> print(proper_round(4.499999999))
4.0
>>> print(proper_round(5.499999999))
5.0

Finally, the corrected answer would be:

# Having proper_round defined as previously stated
h = int(proper_round(h))

Tests:

>>> proper_round(6.39764125, 2)
6.31 # should be 6.4
>>> proper_round(6.9764125, 1)
6.1 # should be 7

The gotcha here is that the dec-th decimal can be 9 and if the dec+1-th digit >=5 the 9 will become a 0 and a 1 should be carried to the dec-1-th digit.

If we take this into consideration, we get:

def proper_round(num, dec=0):
num = str(num)[:str(num).index('.')+dec+2]
if num[-1]>='5':
a = num[:-2-(not dec)] # integer part
b = int(num[-2-(not dec)])+1 # decimal part
return float(a)+b**(-dec+1) if a and b == 10 else float(a+str(b))
return float(num[:-1])

In the situation described above b = 10 and the previous version would just concatenate a and b which would result in a concatenation of 10 where the trailing 0 would disappear. This version transforms b to the right decimal place based on dec, as a proper carry.

pandas, numpy round down to nearest 100

You need divide by 100, convert to int and last multiple by 100:

df['new_values'] = (df['old_values'] / 100).astype(int) *100

Same as:

df['new_values'] = (df['old_values'] / 100).apply(np.floor).astype(int) *100

Sample:

df = pd.DataFrame({'old_values':[8450, 8470, 343, 573, 34543, 23999]})
df['new_values'] = (df['old_values'] / 100).astype(int) *100
print (df)
old_values new_values
0 8450 8400
1 8470 8400
2 343 300
3 573 500
4 34543 34500
5 23999 23900

EDIT:

df = pd.DataFrame({'old_values':[3, 6, 89, 573, 34, 23]})
#show output of first divide for verifying output
df['new_values1'] = (10000/df['old_values'])
df['new_values'] = (10000/df['old_values']).div(100).astype(int).mul(100)
print (df)
old_values new_values1 new_values
0 3 3333.333333 3300
1 6 1666.666667 1600
2 89 112.359551 100
3 573 17.452007 0
4 34 294.117647 200
5 23 434.782609 400

Python: How to round 123 to 100 instead of 100.0?

int(round(123,-2))

The int function can be used to convert a string or number to a plain integer.

Round to the nearest 500, Python

Scale, round, unscale:

round(x / 500.0) * 500.0

Edit: To round up to the next multiple of 500, use the same logic with math.ceil() instead of round():

math.ceil(x / 500.0) * 500.0


Related Topics



Leave a reply



Submit