Floating numbers

Gary Herron gherron at islandtraining.com
Thu Aug 12 23:23:37 CEST 2010

On 08/12/2010 01:43 PM, Bradley Hintze wrote:
> Hi all.
> Is there a way I can keep my floating point number as I typed it? For
> example, I want 34.52 to be 34.52 and NOT 34.5200000002.

Is this a Python question?

The answer is both Yes and No. The binary floating point representation 
of numbers on a computer cannot exactly represent most decimal number 
you would like to type. (Similar to the fact that you cannot represent 
1/3 exactly in a decimal system.)

But that's the internal representation, over which you have no control. 
You do, however, have control over how a number is displayed when printed.

Python 2: Choose a format that displays the exact number of digits you want
'%.2f' % a
or let str(a) choose
but not repr(a) which tries to get all the digits.
(Adding to the confusion, you might also find it confusing to understand 
which of str() or repr() Python chooses to display a number.)

Python 3: Python3 uses David Gay’s algorithm for chosing how to display 
floats. Both str(a) and repr(a) produce '34.52' for your example, which 
is probably just what you want.

Gary Herron

More information about the Python-list mailing list