1

I wrote a simple function to round down a number based on a certain number of decimal places by using the built-in round function and subtracting the last decimal by 1 if it rounds up.

def rounddown(number, places):
    rounded = round(number, places)
    if rounded > number:
        string = '1'
        for x in range(places):
            string = string + '0'
        return rounded - (1/float(string))
    else:
        return rounded

my problem is sometimes the results end up being a number like this:

rounddown(4.555756, 5)

4.555750000000001

Could someone explain to me exactly what is going on here? I think it may have something to do with floating point math inaccuracy?

Thank you

Shion
  • 319
  • 4
  • 12

1 Answers1

0

The issue is basically Floating point operations ,to avoid the problem Please use the decimal library as shown below

from decimal import Decimal
def rounddown(number, places):
    rounded = round(number, places)
    if rounded > number:
        string = '1'
        for x in range(places):
            string = string + '0'
        return Decimal(str(rounded))-1/Decimal(string)
    else:
        return rounded