0

Possible Duplicate:
python limiting floats to two decimal points

If I make this: 12.45-12

in Python the answer I get is: 0.44999999999999929

I do I do it to make it: 0.45?

BTW I did remember to do: 12.45-12.0 But no result.

Community
  • 1
  • 1
petermlm
  • 930
  • 4
  • 12
  • 27
  • 2
    Duplicate. Please SEARCH for Floating-Point in Python. PLease. Are you talking about currency? Money? Use `decimal`. – S.Lott Nov 10 '10 at 11:03

3 Answers3

5

This is a result of the fact that many decimals cannot be exactly represented in binary.

For example, 0.25 can: it's 0.01 (0*1, 0*1/2, 1*1/4). 0.1 can't (0.0001100110011...), just like you can't write 1/3 as a complete decimal (0.3333333333...).

If you do

print(12.45-12)

you get

0.45

because print only displays the first significant digits.

See the Python docs for an excellent summary.

If you do care about decimal values being exact (for example to avoid a Superman III scenario in a financial institution), look at the Decimal module.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
2

It's perfectly OK, but you need to google (and search around on StackOverflow) for "IEEE 754".

EDIT: Take a look e.g. here: Inaccurate Logarithm in Python or here: Another floating point question

Community
  • 1
  • 1
Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83
2

Also in Python 2.4 up, check out the decimal module if you need more accuracy.

mavnn
  • 9,101
  • 4
  • 34
  • 52