0

I wrote below code to convert float variable to integer one:

float myFloat = 45.3F;
int num = (int)(myFloat * 100);

But it returned wrongly 4529 for num variable! And if I change it to:

float myFloat = 23.1F;
int num = (int)(myFloat * 100);

it returns correctly 2310 for num. I solved the problem by using double instead of float. But I want to know what the reason is. Thanks.

IndustProg
  • 627
  • 1
  • 13
  • 33
  • The reason is [float precision](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/float) – lolbas Jan 29 '18 at 10:50
  • You should have a look at [Jon Skeet's article](http://csharpindepth.com/Articles/General/FloatingPoint.aspx) about `floating points`. It's a really good and detailed explanation. – L. Guthardt Jan 29 '18 at 10:52
  • @L.Guthardt, useful article! Thanks. So the correct solution is using `double` type rather than `float` one? – IndustProg Jan 29 '18 at 10:59
  • @GntS No, I think you didn't understand the topic yet. Using `double` won't solve the problem. Imagine you decalre `double x` and you assign `x` the value of `2/3`, what number shell `x` contain? It will try to get with its 64 bits as close to `2/3` as it can, but it will never reach an *exact specific result*. Since 0.6666...6666 is *no spefic number*. If you calculate with it and speficy just some fractional digits, like 3, you will get 0.667. It always tries to get as close as it can calcualte your number, but some floating point values cant be created as you want them to be. – L. Guthardt Jan 29 '18 at 11:06

0 Answers0