Why does (float)1.11111111 = 1.11111116
in C#?
-
4Welcome to the floating point oddities :) If you do not want to struggle with it because you do not need it, use a fixed precision type, neither float nor double. [This SO question](http://stackoverflow.com/questions/605124/fixed-point-math-in-c) may help. – Seki Apr 17 '12 at 08:19
-
To understand what data type would be the best fit for you, we would need to know what you are trying to represent with it. If you update your question I'm sure someone can then make a suggestion. – Adam Houldsworth Apr 17 '12 at 08:23
-
Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – phuclv Nov 30 '20 at 06:21
-
another duplicate: [Why IEEE754 single-precision float has only 7 digit precision?](https://stackoverflow.com/q/19130396/995714) – phuclv Aug 14 '21 at 05:59
2 Answers
Floats have 7 digit precision and are only approximations of actual numbers; equality and other operators don't always work as you would expect, though they are working perfectly fine.
The obligatory link: What Every Computer Scientist Should Know About Floating-Point Arithmetic
There is the Epsilon
property on floats that can be used to help mitigate very small fractional issues with float values, though I have never used it. I'll admit my experience with floating point numbers is limited.
If you need more precision, double
is larger with 15-16 digit precision. If you need even more precision and specifically across base-10 numbers (such as for currency calculations), use decimal
.

- 63,413
- 11
- 150
- 187
-
-
1@Marcel1997 Yeah I need to correct this, `decimal` is not integral, it is actually a decimal floating point as opposed to binary floating point number. – Adam Houldsworth Aug 05 '16 at 07:57
Because a float is NOT an exact value: Wikipedia explains it pretty much. Also make sure you watch Jon Skeet's video from around 6:00 to 10:00. In short: Use floats/doubles for continuous values, decimals/integers etc. for discrete values.

- 8,488
- 2
- 43
- 93
-
-
Thanks all for the answers. In understanding the problem I found these links very useful: http://floating-point-gui.de http://stackoverflow.com/questions/618535/what-is-the-difference-between-decimal-float-and-double-in-c In conculsion I'll use decimal for when I want to do arithmetic with rational numbers. – Apr 18 '12 at 14:57