Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Flooring floats

Tags:

python

math

floor

This is a really simple question. Lets denote the following:

>>> x = 1.2876

Now, round has this great optional second parameter that will round at that decimal place:

>>> round(x,3)
1.288

I was wondering if there is a simple way to round down the numbers. math.floor(x,3) returns an error rather than 1.287

like image 982
Ryan Saxe Avatar asked Dec 25 '22 18:12

Ryan Saxe


1 Answers

This may be the easiest, if by "rounding down" you mean "toward minus infinity" (as floor() does):

>>> x = 1.2876
>>> x - x % .001
1.287
>>> x = -1.1111
>>> x - x % .001
-1.112

This is prone to lots of shallow surprises, though, due to that most decimal values cannot be exactly represented as binary floating-point values. If those bother you, do something similar with decimal.Decimal values instead.

like image 64
Tim Peters Avatar answered Dec 28 '22 10:12

Tim Peters