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
I wrote a code in which a variable is a number, but Im asked to always round it below. How do I do this, since "round" will round it to the nearest?
Greetings,
Code: x = round(7.85, 2) print(x)
Result: 7.8
Why is that? Rounding down starts at 0 and ends at 4, and rounding up begins at 5 and ends at 9. The result should be 7.9.
Does Python have its own math rules? If so, why? Math is math...
Please and thank you ☺