LebGeeks

A community for technology geeks in Lebanon.

You are not logged in.

#1 November 8 2013

NuclearVision
Member

[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?

Offline

#2 November 8 2013

Joe
Member

Re: [python] Dealing with floats?

Short answer: it's normal.
Long answer: read this.

Offline

#3 November 8 2013

NuclearVision
Member

Re: [python] Dealing with floats?

Thanks. Didn't expect it had a dedicated site.

Offline

#4 November 8 2013

Joe
Member

Re: [python] Dealing with floats?

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.

Offline

#5 November 8 2013

NuclearVision
Member

Re: [python] Dealing with floats?

Thanks again.

Offline

#6 November 8 2013

arithma
Member

Re: [python] Dealing with floats?

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

Offline

#7 November 8 2013

NuclearVision
Member

Re: [python] Dealing with floats?

Thanks arithma your trick will do for the moment.

Offline

#8 November 8 2013

m0ei
Member

Re: [python] Dealing with floats?

You can do something like this:

def dec(n):
    return float(format(n - int(n), '.2f'))

Offline

#9 November 10 2013

NuclearVision
Member

Re: [python] Dealing with floats?

m0ei wrote:

You can do something like this:

def dec(n):
    return float(format(n - int(n), '.2f'))

Thanks : )

Offline

Board footer