Search code examples
pythonnumbersrounding

Rounding a float number in python


I have a float numer

a = 1.263597

I hope get

b = 1.2635

But when I try

round (a,4)

then result is

1.2636

What should I do?


Solution

  • Try math.floor with this small modification -

    import math
    
    def floor_rounded(n,d):
        return math.floor(n*10**d)/10**d
    
    n = 1.263597
    d = 4
    
    output = floor_rounded(n,d)
    print(output)
    
    1.2635
    

    For your example, you can just do math.floor(1.263597 * 10000)/10000


    EDIT: Based on the valid comment by @Mark, here is another way of solving this, but this time forcing the custom rounding using string operations.

    #EDIT: Alternate approach, based on the comment by Mark Dickinson
    
    def string_rounded(n,d):
        i,j = str(n).split('.')
        return float(i+'.'+j[:d])
    
    n = 8.04
    d = 2
    
    output = string_rounded(n,d)
    output
    
    8.04