0

We have an array having items from a ienumerator object. One of the field is of type float. While trying to get the index of an item using Array.FindIndex on the float field, It is working fine if it is having 2 digits precisions (ex: 23.34), but if the precession is more than 2 digits (ex: 23.345) it is returning -1.

following is what we are doing:

var items = customer.orders.OrderBy(o => o.price).ToArray();

foreach (var order in object.orders)
{
    int itemIndex= Array.FindIndex(items , i => i.price == order.price);
    
}

in the above example, if the price = 50.64 then Array.FindIndex returns exact index from the items array. But if the price = 50.654 (with more than 2 digits of precesion) it is returning -1 as index (means item not found in array).

Any simple way to solve this issue???

Thanks!!!

Sainath
  • 19
  • 7
  • Floats can’t always be compared directly. You may have to use a different way of comparison for them in your search if you want to do it this way. There might be a more efficient way of doing things anyway but it’s not clear from the example what comes after – Sami Kuhmonen Aug 03 '22 at 13:51
  • Does this answer your question? [Floating point comparison functions for C#](https://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp) also https://stackoverflow.com/questions/1530069/comparing-floating-point-values – Charlieface Aug 03 '22 at 14:37
  • the issue is eventhough item exists in the array, it is returning -1 as index. Due to that, the rest of the code logic will not be executed (as it returns as item doesn't exists) – Sainath Aug 03 '22 at 14:41

1 Answers1

0

When handling decimal data (such as money) it is best to not use float due to the possibility of rounding errors. Decimal is generally more suited to handle these sorts of things

From the documentation on float:

unexpected rounding errors can occur in arithmetic calculations when you use double or float for decimal data.

source

These rounding errors are also why it isn't matching in your array.

Daniel
  • 1
  • 1
  • Thanks!!! for the suggestions. Can we convert it to decimal before comparing. Is it a best practice or do we need to change the type to decimal itself instead of float? I tried this Array.FindIndex(items , i => (decimal)i.price == (decimal)order.price) Now it is returning index and working as expected. – Sainath Aug 03 '22 at 16:28
  • If possible I would recommend changing the type to decimal due to the possibility of having rouding errors when doing things such as adding / dividing etc. – Daniel Aug 04 '22 at 17:13