How does one round a number UP in Python?
I tried round(number)
but it rounds the number down. Example:
round(2.3) = 2.0
and not 3, as I would like.
The I tried int(number + .5)
but it round the number down again! Example:
int(2.3 + .5) = 2
Step 1: Circle the place value of the digit to be rounded. This is the rounding digit. Step 2: Look to the neighboring digit on the right. Step 3: a) If the neighboring digit is less than five (0 - 4), keep the rounding digit the same.
To round a number to the nearest whole number, you have to look at the first digit after the decimal point. If this digit is less than 5 (1, 2, 3, 4) we don't have to do anything, but if the digit is 5 or greater (5, 6, 7, 8, 9) we must round up.
If the smallest place digit is greater than or equal to 5, then round up the digit. As the digit in the smallest digit is less than 5, the digit gets rounded down. So the final number is 0.6.
If you round an amount up, you change it to the nearest whole number or nearest multiple of 10, 100, 1000, and so on. Round up the total price to the nearest dollar.
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)))
I know this answer is for a question from a while back, but if you don't want to import math and you just want to round up, this works for me.
>>> int(21 / 5)
4
>>> int(21 / 5) + (21 % 5 > 0)
5
The first part becomes 4 and the second part evaluates to "True" if there is a remainder, which in addition True = 1; False = 0. So if there is no remainder, then it stays the same integer, but if there is a remainder it adds 1.
Interesting Python 2.x issue to keep in mind:
>>> import math
>>> math.ceil(4500/1000)
4.0
>>> math.ceil(4500/1000.0)
5.0
The problem is that dividing two ints in python produces another int and that's truncated before the ceiling call. You have to make one value a float (or cast) to get a correct result.
In javascript, the exact same code produces a different result:
console.log(Math.ceil(4500/1000));
5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With