Decimal Value Check if Zero

17,950

Solution 1

You can do a conditional if statement like this. This is the same as IIF in VB.net

return dividend / ((divisor == 0) ? 1 : divisor);

Make sure you wrap your second half with () or you will get a divide error.

Solution 2

By using the ?: operator

return (divisor == 0) ? dividend : dividend / divisor 

Solution 3

This is pretty much the same as an if statement, but it is cleaner.

return dividend / divisor == 0 ? 1 : divisor;
Share:
17,950
Jakub Šturc
Author by

Jakub Šturc

Updated on June 09, 2022

Comments

  • Jakub Šturc
    Jakub Šturc almost 2 years

    I am trying to write a division method, which accepts 2 parameters.

    public static decimal Divide(decimal divisor, decimal dividend)
    {
        return dividend / divisor;
    }
    

    Now, if divisor is 0, we get cannot divide by zero error, which is okay.

    What I would like to do is check if the divisor is 0 and if it is, convert it to 1. Is there way to do this with out having a lot of if statements in my method? I think a lot of if()s makes clutter. I know mathematically this should not be done, but I have other functionality for this.

    For example:

    if(divisor == 0)
    {
        divisor = 1;
    }
    return dividend / divisor;
    

    Can it be done without the if() statement?

    • Mike Kale
      Mike Kale almost 15 years
      I guess this is your problem domain, but consider that your code is going to be returning a very different result if the divisor makes the very minor change from 0.000001 to 0.0
    • Peter Gfader
      Peter Gfader almost 15 years
      I prefer YOUR code, than the conditional if statements. Much easier to read!! And that's what I want
  • Michael Stum
    Michael Stum almost 15 years
    +1 for pointing out that a division by 1 is unnecessary and just return the divident.
  • Brian Rasmussen
    Brian Rasmussen almost 15 years
    You don't need two set of parentheses do you? return dividend / (divisor == 0 ? 1 : divisor); should do the trick
  • CodeLikeBeaker
    CodeLikeBeaker almost 15 years
    No, I had an additional set you can do it like this as well: return dividend / (divisor == 0 ? 1 : divisor);
  • CodeLikeBeaker
    CodeLikeBeaker almost 15 years
    But you do need the () wrapping the value of the result, other wise you still get the divide by zero error
  • Alexander Kahoun
    Alexander Kahoun almost 15 years
    @Brian - no, you don't need the two sets, you are correct. On the flip side though I sometimes find Jason's approach more readable.
  • napster
    napster almost 15 years
    If in doubt, add parentheses.
  • Peter Gfader
    Peter Gfader almost 15 years
    this is not cleaner than an If statement
  • FlamePrinz
    FlamePrinz over 2 years
    This will cause an error if the divisor is 0.