Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between int() and floor() in Python 3?

In Python 2, floor() returned a float value. Although not obvious to me, I found a few explanations clarifying why it may be useful to have floor() return float (for cases like float('inf') and float('nan')).

However, in Python 3, floor() returns integer (and returns overflow error for the special cases mentioned before).

So what is the difference, if any, between int() and floor() now?

like image 324
datah4ck3r Avatar asked Jun 24 '15 20:06

datah4ck3r


People also ask

What is the difference between int and floor?

Putting it differently, the floor() is always going to be lower or equal to the original. int() is going to be closer to zero or equal.

How do you int a floor in Python?

The floor() function: floor() method in Python returns the floor of x i.e., the largest integer not greater than x. Syntax: import math math. floor(x) Parameter: x-numeric expression. Returns: largest integer not greater than x.

What does the floor function do Python?

floor() method rounds a number DOWN to the nearest integer, if necessary, and returns the result.


1 Answers

floor() rounds down. int() truncates. The difference is clear when you use negative numbers:

>>> import math >>> math.floor(-3.5) -4 >>> int(-3.5) -3 

Rounding down on negative numbers means that they move away from 0, truncating moves them closer to 0.

Putting it differently, the floor() is always going to be lower or equal to the original. int() is going to be closer to zero or equal.

like image 156
Martijn Pieters Avatar answered Sep 28 '22 07:09

Martijn Pieters