Integer Division

  • Thread starter Anjanesh Lekshminarayanan
  • Start date
M

Mark Dickinson

0.040000000000000001

Python typically stores floats in binary, not decimal. The
value 0.04 isn't exactly representable in binary, so the
division float(1)/25 can't produce 0.04: what you get instead
is a very good approximation to 0.04. That's why you're
seeing what you're seeing above. Note that 0.0400...001 is
*also* just an approximation to the actual value stored, but
it's a better approximation than 0.04. The exact value stored
is (probably, assuming your machine is typical):

0.040000000000000000832667268468867405317723751068115234375

or, if you prefer, it's:

5764607523034235/144115188075855872
In what simple way can I get just 0.04 ?

The answer to that depends on what you want and why you
want it. Do you want a string or a number? And if you
want a number, does it have to be *exactly* 0.04, or
can your application cope with a tiny error?

If you're trying to get a string and just want things
to look nice, use str() instead of repr(),
or display the value using print. If you want more control
over the number of digits displayed, use Python's string
formatting: e.g., in Python 2.6:
'0.040'

See the following for more information on format:

http://docs.python.org/library/string.html#formatstrings

If you're after the number and you *really* need to
be able to manipulate the *exact* value 0.04 in Python
(e.g., because you're doing financial work), you're probably
better off using the Decimal module:

http://docs.python.org/library/decimal.html

See also:

http://docs.python.org/tutorial/floatingpoint.html

Mark
 
P

Piet van Oostrum

AL> In what simple way can I get just 0.04 ?

In addition to the answers others have given:

IIRC, Python 3.1 will give 0.04. But this doesn't mean the answer will
be mathematically equal to 0.04, just that it tries to make it less
painful.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top