1/2
gives
0
as it should. However,
-1/2
gives
-1
, but I want it to round towards 0 (i.e. I want -1/2 to be 0), regardless of whether it's positive or negative. What is the best way to do that?
In Python, we can perform floor division (also sometimes known as integer division) using the // operator. This operator will divide the first argument by the second and round the result down to the nearest whole number, making it equivalent to the math. floor() function.
If the divisor and dividend have the same sign then the result is zero or positive. If the divisor and dividend have opposite signs then the result is zero or negative. If the division is inexact then the quotient is rounded towards zero. That is, up if it is negative, and down if it is positive.
Round-toward-zero: As its name suggests, this refers to rounding in such a way that the result heads toward zero. For example, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, and 3.9 will all be rounded to 3. Similarly, -3.1, -3.2, -3.3, -3.4, -3.5, -3.6, -3.7, -3.8, and -3.9 will all be rounded to -3.
Some programming languages give up (3), and make div round down (Python, Ruby). In some (rare) cases the language offers multiple division operators.
Do floating point division then convert to an int. No extra modules needed.
Python 3:
>>> int(-1 / 2) 0 >>> int(-3 / 2) -1 >>> int(1 / 2) 0 >>> int(3 / 2) 1
Python 2:
>>> int(float(-1) / 2) 0 >>> int(float(-3) / 2) -1 >>> int(float(1) / 2) 0 >>> int(float(3) / 2) 1
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