floating point rounding

H

hg

Hi,

Here is my issue:

f = 1.5 * 0.01
f

But I really want to get 0.02 as a result ... is there a way out ?

Thanks,

hg
 
G

greg

John said:
Or more precisely:

round(0.014999999999999999,2)

No, that *won't* solve the problem. Using a slightly
different example,
0.14999999999999999

The problem is that floats are stored internally in
binary, not decimal, and numbers like 0.1 and 0.01
have no exact representation as a binary float.
Using round() doesn't help, because the result is
still a binary float, and the result you're after
still can't be represented.

The best you can do is to *display* it rounded
to the number of digits you want using formatting,
e.g.
'0.15'

Alternatively, use the Decimal module, which stores
numbers as decimal and does arithmetic in ways that
will match your calculator. It's slower, though.
 

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,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top