5

Trying to cast float to int but there's something missing

float submittedAmount = 0.51f;

int amount = (int)(submittedAmount * 100);

here is watch. look at the variable values

Why is the answer 50?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
levi
  • 3,451
  • 6
  • 50
  • 86

4 Answers4

5

Because of floating point aritmethics, the multiplied value isn't exactly 51. When I tried now, *0.51f * 100* gave the result 50.9999990463257.

And when you parse 50.9999990463257 to and int, you surely get 50.

If you want calculations like this to be exact, you will have to use a type like decimal instead of float.

If you want to understand why, read the article I have linked below.

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
1

Try with

int amount = (int)(submittedAmount * 100.0);

When you write 0.51f is not exactly 0.51

Read this great article called What Every Computer Scientist Should Know About Floating-Point Arithmetic

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

Use Convert class. Otherwise the answer still will be 50.

 var amount  = Convert.ToInt32(submittedAmount * 100.0));
Tormod
  • 4,551
  • 2
  • 28
  • 50
0

0.51f is actually 0.509999999999. because floating points are imprecise.

I would like to add that, do not use float for monetary calculations. Use decimal instead.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78