Rounding a float number in python

Question:

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?

Asked By: duy dang

||

Answers:

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
Answered By: Akshay Sehgal

Plain Python without importing any libraries (even not standard libraries):

def round_down(number, ndigits=None):
    if ndigits is None or ndigits == 0:
        # Return an integer if ndigits is 0
        return int(number)
    else:
        return int(number * 10**ndigits) / 10**ndigits

a = 1.263597
b = round_down(a, 4)
print(b)
1.2635

Note that this function rounds towards zero, i.e. it rounds down positive floats and rounds up negative floats.

Answered By: andthum
def round_down(number, ndigits=0):
    return round(number-0.5/pow(10, ndigits), ndigits)

Run:

round_down(1.263597, 4)
>> 1.2635
Answered By: Farid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.