Search code examples
c#intdoublesubtraction

Subtracting int from double leads to an error


I have an int and a double, but as soon as I try to subtract the integer from the double, the following error is thrown:

Input string was not in a correct format.

Now lets look at the code:

double TotalNoRegis = values.Sum(); // This is a LIST and its = 1569
string otherFe ="600";
double totalafter;
if(otherFe != string.Empty || otherFe!= "") // This part works fine
{
    totalafter =  TotalNoRegis - Convert.ToInt32(otherFe); // Here the error is thrown
}

What am I doing wrong here? I looked at this Example, which is basically the same thing: int x = 1 and int y = 2 and then int this = x-y;

Please let me know if you know the issue here.


Solution

  • What am I doing wrong here?

    Lots.

    if(otherFe != string.Empty || otherFe!= "") // This part works fine
    

    That's nonsensical code. string.Empty and "" are the same string.

    Instead use

    if (!string.IsNullOrEmpty(otherFe))
    

    Moving on:

    totalafter =  TotalNoRegis - Convert.ToInt32(otherFe); // Here the error is thrown
    

    You claim that the error is the subtraction, but it is not. The problem is in the ToInt32. You are passing some other string than the one you are showing.

    The way I like to do this is by making an extension method:

    static public class Extensions 
    {
        public static int? ParseAsInteger(this string s) {
            if (string.IsNullOrEmpty(s)) return null;
            int i;
            return int.TryParse(s, out i) ? (int?)i : (int?)null;
        }
        // Similarly write `ParseAsDouble` and so on.
    }
    

    Now you have an extension you can use:

    double? totalAfter = TotalNoRegis - otherFe.ParseAsInteger();
    

    (Or ParseAsDouble, or whatever.)

    If otherFe was valid, then totalAfter has the total; if it was not, then it is null.

    The lesson here is: move the type conversion logic into its own method which you can independently test. Then the logic at the call site of that method becomes simpler and easier to follow.