If x is a float number that you want to round up to an integer, and you want an integer type result, you could use
rounded_up_x = int(-(-x // 1))
This works because integer division by one rounds down, but using the negative sign before and after doing the division rounds the opposite direction. The int here converts the float result to an integer. Remove that int if you want a floating point value that equals an integer, which is what some programming languages do.
Hat-tip to @D.LaRocque for pointing out that Python's ceil() function returns an integer type.
Videos
If x is a float number that you want to round up to an integer, and you want an integer type result, you could use
rounded_up_x = int(-(-x // 1))
This works because integer division by one rounds down, but using the negative sign before and after doing the division rounds the opposite direction. The int here converts the float result to an integer. Remove that int if you want a floating point value that equals an integer, which is what some programming languages do.
Hat-tip to @D.LaRocque for pointing out that Python's ceil() function returns an integer type.
in Python 3, we have object.__ceil__() that is even called by math.ceil internally,
num = 12.4 / 3.3
print(num)
3.757575757575758
num.__ceil__()
4
Or one can always negate the result of a negated number's floor division (and create a new int object unless a float would do),
int(-(-12.4 // 3.3))
4
int(x)
Conversion to integer will truncate (towards 0.0), like math.trunc.
For non-negative numbers, this is downward.
If your number can be negative, this will round the magnitude downward, unlike math.floor which rounds towards -Infinity, making a lower value. (Less positive or more negative).
Python integers are arbitrary precision, so even very large floats can be represented as integers. (Unlike in other languages where this idiom could fail for floats larger than the largest value for an integer type.)
One of these should work:
import math
math.trunc(1.5)
> 1
math.trunc(-1.5)
> -1
math.floor(1.5)
> 1
math.floor(-1.5)
> -2
I had this python challenge in class where we had to take input from a user to see what digits to round pi to and we had to print the result without using the round() function. so for example if the input was 5, then it would print out 3.14159. im not sure how to do it without using round(). I tried using {:.f} string formatting but I cannot insert a variable, only a number
You can us either int(), math.trunc(), or math.floor(). They all will do what you want for positive numbers:
>>> import math
>>> math.floor(12.6) # returns 12.0 in Python 2
12
>>> int(12.6)
12
>>> math.trunc(12.6)
12
However, note that they behave differently with negative numbers: int and math.trunc will go to 0, whereas math.floor always floors downwards:
>>> import math
>>> math.floor(-12.6) # returns -13.0 in Python 2
-13
>>> int(-12.6)
-12
>>> math.trunc(-12.6)
-12
Note that math.floor and math.ceil used to return floats in Python 2.
Also note that int and math.trunc will both (at first glance) appear to do the same thing, though their exact semantics differ. In short: int is for general/type conversion and math.trunc is specifically for numeric types (and will help make your intent more clear).
Use int if you don't really care about the difference, if you want to convert strings, or if you don't want to import a library. Use trunc if you want to be absolutely unambiguous about what you mean or if you want to ensure your code works correctly for non-builtin types.
More info below:
Math.floor() in Python 2 vs Python 3
Note that math.floor (and math.ceil) were changed slightly from Python 2 to Python 3 -- in Python 2, both functions will return a float instead of an int. This was changed in Python 3 so that both methods return an int (more specifically, they call the __float__ method on whatever object they were given). So then, if you're using Python 2, or would like your code to maintain compatibility between the two versions, it would generally be safe to do int(math.floor(...)).
For more information about why this change was made + about the potential pitfalls of doing int(math.floor(...)) in Python 2, see
Why do Python's math.ceil() and math.floor() operations return floats instead of integers?
int vs math.trunc()
At first glance, the int() and math.trunc() methods will appear to be identical. The primary differences are:
- int(...)
- The int function will accept floats, strings, and ints.
- Running
int(param)will call theparam.__int__()method in order to perform the conversion (and then will try calling__trunc__if__int__is undefined) - The
__int__magic method was not always unambiguously defined -- for some period of time, it turned out that the exact semantics and rules of how__int__should work were largely left up to the implementing class. - The
intfunction is meant to be used when you want to convert a general object into an int. It's a type conversion method. For example, you can convert strings to ints by doingint("42")(or do things like change of base:int("AF", 16) -> 175).
- math.trunc(...)
- The trunc will only accept numeric types (ints, floats, etc)
- Running
math.trunc(param)function will call theparam.__trunc__()method in order to perform the conversion - The exact behavior and semantics of the
__trunc__magic method was precisely defined in PEP 3141 (and more specifically in the Changes to operations and __magic__ methods section). - The
math.truncfunction is meant to be used when you want to take an existing real number and specifically truncate and remove its decimals to produce an integral type. This means that unlikeint,math.truncis a purely numeric operation.
All that said, it turns out all of Python's built-in types will behave exactly the same whether you use int or trunc. This means that if all you're doing is using regular ints, floats, fractions, and decimals, you're free to use either int or trunc.
However, if you want to be very precise about what exactly your intent is (ie if you want to make it absolutely clear whether you're flooring or truncating), or if you're working with custom numeric types that have different implementations for __int__ and __trunc__, then it would probably be best to use math.trunc.
You can also find more information and debate about this topic on Python's developer mailing list.
you can do this easily with a built in python functions, just use two forward slashes and divide by 1.
>>> print 12.75//1
12.0
>>> print 1.999999999//1
1.0
>>> print 2.65//1
2.0