## Why I'm getting 9999s after decimal and how do I fix it?

1

Check the screen shot. Why I'm getting 999s? It is suppose to be 127,977.52

Quick solution: AccountingForm[58156.48 + 69821.04, 16]

And thanks to Yves Klett

Question was closed 2014-11-24T18:22:37.753

1Welcome! The bugs tag is for confirmed bugs only. – Yves Klett – 2014-11-24T17:16:34.407

Not to worry. What you are seeing is not a bug but a result of machine precision arithmetic. This is actually a duplicate of http://mathematica.stackexchange.com/q/5580/131. Also useful: http://floating-point-gui.de/basic/

– Yves Klett – 2014-11-24T17:20:06.673

There are only two digits after decimal in the input, so ideally it output only 2 digits for additions or subtractions. Is there a way to get output like 127,977.52 in the above case? – Kruz – 2014-11-24T17:24:52.680

Thanks checking those links, when I posted didn't saw those links. – Kruz – 2014-11-24T17:25:38.773

The only way to "fix" this would be to use exact numbers. Most of the time this will not be neccessary however.

– Yves Klett – 2014-11-24T17:27:17.547

Thanks for the help :) For quick solution this one works for me AccountingForm[58156.48 + 69821.04, 16] – Kruz – 2014-11-24T17:48:24.003

3

This is a problem for anything that uses machine precision floats, e.g. Mathematica, Matlab, C, etc.

Consider the simpler example $1/10$. In base 10, this fraction has the finite decimal expansion $$1/10 = 0.1$$ But your machine would store this number (and all floats) in binary. The problem is, in binary $1/10$ has the infinite decimal expansion $$1/10 = \left(0.000\overline{1100}\right)_2$$ This means your machine must to round (since it can't store infinite digits). This introduces error.

Now for your problem, we can see your decimals don't have a finite expansion in binary using RealDigits:

RealDigits[58156.48, 2]

{{1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1,
1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0,
1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1}, 16}

RealDigits[69821.04, 2]

{{1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0,
0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1}, 17}


As Yves said in the comments, a fix in Mathematica is to avoid machine precision and use exact precision. Here I am forcing both numbers to have the first 20 digits correct:

58156.4820 + 69821.0420 // InputForm

127977.5220.


Thanks 58156.4820 + 69821.04`20 // InputForm That is exactly what I was looking for. – Kruz – 2014-11-24T18:58:30.360