Naz-Al Islam - 3 years ago 247

Python Question

The expression

`6 // 4`

`1`

But with a negative number, why does

`-6 // 4`

`-2`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The `//`

operator explicitly *floors* the result. Quoting the *Binary arithmetic operations* documentation:

the result is that of mathematical division with the ‘floor’ function applied to the result.

Flooring is not the same thing as rounding to 0; flooring always moves to the *lower integer value*. See the `math.floor()`

function:

Return the floor of

x, the largest integer less than or equal tox.

For `-6 // 4`

, first the result of `-6 / 4`

is calculated, so `-1.5`

. Flooring then moves to the lower integer value, so `-2`

.

If you want to round towards zero instead, you'll have to do so explicitly; you could do this with the `int()`

function on true division:

```
>>> int(-6 / 4)
-1
```

`int()`

removes the decimal portion, so always rounds towards zero instead.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**