• Coding
  • [python] Dealing with floats?

hello...

I was working on the decimal exercice.
And came up with this:
def dec(n):#trying to separate the integral part from the fraction part
    return float(n)-int(n)
output:
>>> dec(3.8)
0.7999999999999998
Any ideas?
It has so much more than just a dedicated website. Floating number arithmetic is one of the oldest problem computers faced.
The reason is simple: how do you represent 0.1 or 10/3 in binary?

The website I link to is trying to provide a simple answer to this complex problem, that's all.
When I face those issues, I usually decide beforehand the number of decimals I want to use.
>>> print "%.2f" % (3.8-int(3.8))
0.80
You can do something like this:
def dec(n):
    return float(format(n - int(n), '.2f'))
m0ei wroteYou can do something like this:
def dec(n):
    return float(format(n - int(n), '.2f'))
Thanks : )