-2

I have a round function in my code to round a number 5% of the time it does not work properly like in my second example:

Mynumber = round(3.65108567,3)

#Working well
print(Mynumber)
3.651

#Not working
print(Mynumber)
3.65100000000000000001

How can I fix the issue? I work with python 3.7

Emericdt
  • 9
  • 2
  • 2
    I think you need to understand that `3.651 == 3.65100000000000000001` – juanpa.arrivillaga May 13 '21 at 10:30
  • 1
    Does this answer your question? [round() doesn't seem to be rounding properly](https://stackoverflow.com/questions/56820/round-doesnt-seem-to-be-rounding-properly) – user_na May 13 '21 at 10:30
  • 1
    The duplicate isn't a good one. It dates from Python 2 days. It should be rather unusual to see this effect in Python 3, where `round` is correctly rounded and printing uses the shortest-string algorithm. Please could you show the exact code to reproduce the issue? What does `type(Mynumber)` show? And what is the value of `sys.float_repr_style`? Is this CPython or some other flavour of Python? – Mark Dickinson May 13 '21 at 12:07
  • 1
    I can't repro this locally; I suspect you're just seeing the floating point representation of `3.651`. If the goal is simply printing 3 decimals, would formatting solve your problem? e.g. `print(format(3.65108567, ".3f"))` – wrhall May 13 '21 at 15:50

1 Answers1

-1

Try using this code

def round(n , m=2):
    return (n//(10**(-m)))/10**m
wrhall
  • 1,288
  • 1
  • 12
  • 26