How to prevent division by zero?

▼魔方 西西 提交于 2019-12-06 01:06:23

问题


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?


回答1:


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



回答2:


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);


来源:https://stackoverflow.com/questions/10243382/how-to-prevent-division-by-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!