-2

I'm trying to add two floating number and I cannot get to work. I need to be the output to be 100.0 What I'm doing wrong here. Thank you for any advise.

mystring = 'Value:   99.9      Date:    20130215'
tot = float(mystring[8:13])
print (float(tot) + .01)

I need to be the tot = 100.0 if any one can help Thank you

I'm getting 99.91

pirulo
  • 335
  • 1
  • 5
  • 13
  • 8
    99.9 + 0.01 is not 100, it's 99.91 – Ismail Badawi Oct 16 '14 at 18:41
  • I would suggest reading [floating point arthimetic](https://docs.python.org/2/tutorial/floatingpoint.html) documentation – Grice Oct 16 '14 at 18:41
  • 1
    Shouldn't you be adding 0.1 and not 0.01? – pjd Oct 16 '14 at 18:41
  • 2
    I don't think this is a dup. After all, `99.9 + 0.1 == 100.0` is true. Of course the OP should definitely read about float representations and rounding and so on, but it's not actually his problem here, he's just got a silly typo. – abarnert Oct 16 '14 at 18:50
  • Since reopening to reclose lost the link to the useful question about floating point math: http://stackoverflow.com/questions/588004/is-floating-point-math-broken – abarnert Oct 16 '14 at 18:51

1 Answers1

1

Two problems:

  1. adding .01 to 99.9 results in 99.91, not 100.0.
  2. floating point math won't always yield what you think it does, because not all numbers can be represented accurately in floating point. You should never expect the result of a floating pointer operation to be a precise number

For more on (2), see floating point arithmetic

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685