-2

I am performing arithmetic subtraction on the elements of a C# list of type double and it results in some incorrect results sometimes

For example I have three elements in the listTempStrike as follows

3.6
3.7
3.8

So, when I perform listTempStrike[1] - listTempStrike[0] it results 0.1 which is true but when I perform listTempStrike[2] - listTempStrike[1] it returns 0.099999999999999645 which I feel is strange. Any better solution to this?

DoIt
  • 3,270
  • 9
  • 51
  • 103
  • 7
    Welcome to the world of binary floating point numbers. – Servy Sep 04 '14 at 17:20
  • You can either use decimal type instead of double, or simply write Math.Round(listTempStrike[1] - listTempStrike[0], 1), this will round it up to the first decimal – Bedford Sep 04 '14 at 17:25

1 Answers1

2

you will need to change the type to decimal instead of float/double

this should solve your issue

Fredou
  • 19,848
  • 10
  • 58
  • 113