Float value is lost in Int

Trying to throw float in int, but something is missing there

float submittedAmount = 0.51f;

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

here is watch.  look at the variable values

Why is the answer 50?

+5
source share
4 answers

Due to floating point arithmetic, the multiplied value is not exactly 51. When I tried now, * 0.51f * 100 * gave the result 50.9999990463257.

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

If you want the calculations to be accurate, you will need to use a type of type decimalinstead float.

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

What Every Computer Scientist Should Know About Floating-Point Arithmetic

+5
source

Try

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

When you write is 0.51fnot accurate0.51

What Every Computer Scientist Should Know About Floating-Point Arithmetic

+1

Convert. 50.

 var amount  = Convert.ToInt32(submittedAmount * 100.0));
0

0.51fin fact 0.509999999999. because floating points are inaccurate.

I would like to add that do not use floatfor cash settlements. Use instead decimal.

0
source

All Articles