Search code examples
c#operator-precedence

C# double datatype gives a 0 always


I have the following function that typically need to return a value. I calculate the value in a calculator app and I get values just fine. But in the program below the value variable value is always 0. I have tried using long, double, float but nothing works. Please help.

 public string CalculateElapsedPercent(DateTime endTime, DateTime startTime)
        {
            string result = string.Empty;
            DateTime currentTime = DateTime.Now;
            if (currentTime > endTime)
            {
                result = " (100 %)";
                return result;
            }
            long nr = (currentTime - startTime).Ticks;
            long dr = (endTime - startTime).Ticks;
            double value = (nr / dr) * 100.0;
            result = " (" + value.ToString() + " %)";
            return result;
        }

Solution

  • Since both nr and dr are long, the result of (nr / dr) is long, and since dr is greater that nr, the result is equal to 0.

    In order to fix that, you can convert it to double during calculation:

    double value = ((double)nr / (double)dr) * 100.0;
    

    Or you can define nr and dr as doubles:

    double nr = (currentTime - startTime).Ticks;
    double dr = (endTime - startTime).Ticks;
    double value = (nr / dr) * 100.0;
    

    The behavior in your original code sample is called integer division. See Division operator article in C# Specification or Why integer division in c# returns an integer but not a float? stackoverflow question for more info