Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

float.Parse returns incorrect value [duplicate]

I have a string X with value 2.26

when I parse it using float.Parse(X) ..it returns 2.2599999904632568. Why so? And how to overcome this ?

But if instead I use double.Parse(X) it returns the exact value, i.e. 2.26.

EDIT: Code

float.Parse(dgvItemSelection[Quantity.Index, e.RowIndex].Value.ToString());

Thanks for help

like image 458
Marshal Avatar asked Jul 26 '26 16:07

Marshal


2 Answers

This is due to limitations in the precision of floating point numbers. They can't represent infinitely precise values and often resort to approximate values. If you need highly precise numbers you should be using Decimal instead.

There is a considerable amount of literature on this subject that you should take a look at. My favorite resource is the following

  • What Every Computer Scientist Should Know About Floating Point
like image 143
JaredPar Avatar answered Jul 28 '26 07:07

JaredPar


Because floats don't properly represent decimal values in base 10.

Use a Decimal instead if you want an exact representation.

Jon Skeet on this topic

like image 24
msarchet Avatar answered Jul 28 '26 06:07

msarchet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!