Python - Flooring floats

This is a very simple question. Denote the following:

>>> x = 1.2876

Now roundhas this large optional second parameter, which will be rounded in this decimal place:

>>> round(x,3)
1.288

I was wondering if there is an easy way to round numbers. math.floor(x,3)returns an error, not1.287

+4
source share
5 answers

This is just what appeared in my head. Why don't we convert it to a string and then put it?

import math
def floor_float(x, index):
    sx = str(x)
    sx = sx[:index]+str(math.floor(float(sx[index]+"."+sx[index+1])))
    return float(sx)

A slight advantage is that it more fully reflects the error representation, it is more accurate in the representation of numbers (since this is a string):

>>> floor_float(10.8976540981, 8)
10.897654

This may not be the best pythonic solution though .. But it works very well :)

Python 2.x, math.floor float integer. , :

    sx = sx[:index]+str(int(math.floor(float(sx[index]+"."+sx[index+1]))))

Update2

, ;)

, :

def floor_float(x, i):
    return float(str(x)[:i])
+2

, "" " " ( floor()):

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

, - . , - decimal.Decimal .

+3

floor(x*10**3)*10**-3.

+2

Another approach based on the module is decimalmore sophisticated tools. Like the built-in round(), it also supports negative "digits":

>>> round(1234.5, -1) # builtin behavior for negative `ndigits`
1230.0
>>> round(1234.5, -2)
1200.0
>>> round(1234.5, -3)
1000.0

and you can use any of the 8 (!) rounding modes defined in decimal.

from decimal import ROUND_DOWN
def rfloat(x, ndigits=0, rounding=ROUND_DOWN):
    from decimal import Decimal as D
    proto = D("1e%d" % -ndigits)
    return float(D(str(x)).quantize(proto, rounding))

Example:

for i in range(-4, 6):
    print i, "->", rfloat(-55555.55555, i)

gives:

-4 -> -50000.0
-3 -> -55000.0
-2 -> -55500.0
-1 -> -55550.0
0 -> -55555.0
1 -> -55555.5
2 -> -55555.55
3 -> -55555.555
4 -> -55555.5555
5 -> -55555.55555

Try to analyze the lines yourself at your own risk; -)

+2
source
def roundDown(num, places):
    return int(num*(10**places))/float(10**places)
+1
source

All Articles