Search code examples
c#linqdivide-by-zero

How to prevent division by zero?


ads = ads.Where(x => (x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);

if x.Amount == 0 I have error "Divide by zero error encountered."

like me in this request is to avoid?

update:

this helped, but I do not like the decision:

ads = ads.Where(x => (x.Amount - x.Price) / ((x.Amount / 100)==0?0.1:(x.Amount / 100)) >= filter.Persent);

there is another way?


Solution

  • ads = ads.Where(x => x.Amount != 0 &&
                        (x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);