How to prevent division by zero?

后端 未结 2 1949
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 14:31
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

相关标签:
2条回答
  • 2021-02-15 15:29
    ads = ads.Where(x => x.Amount != 0 &&
                        (x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);
    
    0 讨论(0)
  • 2021-02-15 15:36

    Of course, you can always implement a generic safe division method and use it all the way

    using System;
    
    namespace Stackoverflow
    {
        static public class NumericExtensions
        {
            static public decimal SafeDivision(this decimal Numerator, decimal Denominator)
            {
                return (Denominator == 0) ? 0 : Numerator / Denominator;
            }
        }
    
    }
    

    I have chosen decimal type because it addresses all non nullable numeric types that I am aware of.

    Usage:

    var Numerator = 100;
    var Denominator = 0;
    
    var SampleResult1 = NumericExtensions.SafeDivision(Numerator , Denominator );
    
    var SampleResult2 = Numerator.SafeDivision(Denominator);
    
    0 讨论(0)
提交回复
热议问题