6
votes

My code:

a = '2.3'

I wanted to display a as a floating point value.

Since a is a string, I tried:

float(a)

The result I got was :

2.2999999999999998

I want a solution for this problem. Please, kindly help me.

I was following this tutorial.

3
@rejinacm.myopenid.com: you might want to remove the comment "This is a drawback of Python." ! - Mitch Wheat
-1 to the freaks who downvoted this question instead of fixing it! - David Schmitt

3 Answers

18
votes

I think it reflects more on your understanding of floating point types than on Python. See my article about floating point numbers (.NET-based, but still relevant) for the reasons behind this "inaccuracy". If you need to keep the exact decimal representation, you should use the decimal module.

6
votes

This is not a drawback of python, rather, it is a drawback of the way floating point numbers are stored on a computer. Regardless of implementation language, you will find similar problems.

You say that you want to 'display' A as a floating point, why not just display the string? Visually it will be identical to what you expect.

As Jon mentioned, if your needs are more than just 'displaying' the floating point number, you should use the decimal module to store the exact representation.

4
votes

Excellent answers explaining reasons. I just wish to add a possible practical solution from the standard library:

>>> from decimal import Decimal
>>> a = Decimal('2.3')
>>> print a
2.3

This is actually a (very) F.A.Q. for Python and you can read the answer here.