Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking the floor of a float

I have found two ways of taking floors in Python:

3.1415 // 1 

and

import math math.floor(3.1415) 

The problem with the first approach is that it return a float (namely 3.0). The second approach feels clumsy and too long.

Are there alternative solutions for taking floors in Python?

like image 607
Randomblue Avatar asked Feb 22 '12 23:02

Randomblue


People also ask

How do you get the float floor in Python?

In Python 2, floor(math. pi) returns a float value, whereas in Python 3, an int value is returned. In general, the Python 2 floor() function returns float values, whereas the Python 3 floor() function returns integer values.

How do you take the floor in Python?

The math. floor() method rounds a number DOWN to the nearest integer, if necessary, and returns the result. Tip: To round a number UP to the nearest integer, look at the math. ceil() method.

What does the floor function do?

floor() function returns the largest integer less than or equal to a given number.

What is floor () in C?

Overview. The floor() is a library function in C defined in the <math. h> header file. This function returns the nearest integer value, which is less than or equal to the floating point number (float or double) passed to it as an argument.


2 Answers

As long as your numbers are positive, you can simply convert to an int to round down to the next integer:

>>> int(3.1415) 3 

For negative integers, this will round up, though.

like image 133
Sven Marnach Avatar answered Oct 02 '22 11:10

Sven Marnach


You can call int() on the float to cast to the lower int (not obviously the floor but more elegant)

int(3.745)  #3 

Alternatively call int on the floor result.

from math import floor  f1 = 3.1415 f2 = 3.7415  print floor(f1)       # 3.0 print int(floor(f1))  # 3 print int(f1)         # 3 print int(f2)         # 3 (some people may expect 4 here) print int(floor(f2))  # 3 

http://docs.python.org/library/functions.html#int

like image 38
Matt Alcock Avatar answered Oct 02 '22 10:10

Matt Alcock