Agniswar Bakshi Agniswar Bakshi - 3 months ago 14
Python Question

Printing a float value in python not rounding up

I have to print a number in python of this form :
n = "35.66667"
The output should be "35.666". Now, I tried round() function in python upto 3 decimal places but its giving me incorrect result of 35.667.

Any idea how can i print the float value upto 3 decimal places without rounding up?

Answer

Yes, but that's the question asked. To print the float value upto 3 decimal places without rounding up.

So trim the string representation:

def trim_float(n, d):
    n_str = str(n)
    point_index = n_str.find('.')
    return float(n_str[:point_index + d + 1])

print(trim_float(35.66667, 3))
>> 35.666
Comments