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

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

Thanks in advance,

Quick solution: AccountingForm[58156.48 + 69821.04, 16]

And thanks to Yves Klett

• Welcome! The bugs tag is for confirmed bugs only. – Yves Klett Nov 24 '14 at 17:16
• Not to worry. What you are seeing is not a bug but a result of machine precision arithmetic. This is actually a duplicate of mathematica.stackexchange.com/q/5580/131. Also useful: floating-point-gui.de/basic – Yves Klett Nov 24 '14 at 17:20
• 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 Nov 24 '14 at 17:24
• Thanks checking those links, when I posted didn't saw those links. – Kruz Nov 24 '14 at 17:25
• The only way to "fix" this would be to use exact numbers. Most of the time this will not be neccessary however. – Yves Klett Nov 24 '14 at 17:27

## 1 Answer

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 Nov 24 '14 at 18:58