Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you round UP a number?

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
like image 570
bodacydo Avatar asked Mar 01 '10 14:03

bodacydo


People also ask

How do you round up a number step by step?

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.

How do you round up to a whole number?

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.

What is the round off of 5?

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.

What does it mean to round a number up?

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.


3 Answers

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)))
like image 102
Steve Tjoa Avatar answered Oct 16 '22 00:10

Steve Tjoa


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.

like image 31
user3074620 Avatar answered Oct 16 '22 01:10

user3074620


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
like image 34
TrophyGeek Avatar answered Oct 16 '22 00:10

TrophyGeek