1. Rounding decimal value to 0.0 or 0.5

    Today morning I was need to convert values ranging 0.0 to 1.0 where rounding will be necessary 0.0 or 0.5. For instance, if your original value 7.3 it should be floored to 7.0 and on the other hand if your value is 7.8 it should be floored to 7.5.

    The original code was written by Indian developers where they thousands if-else conditions like

    if (value >= 0.0 && value < 0.5)
         return 0.0;
    else if (value >= 0.5 && value < 1.0)
         return 0.5;
    else if (value >= 1.0 && value < 1.5)
         return 1.0;
    -
    -
    -
    else if (value >= 99.5 && value < 100.0)
         return 100;

    This is one of the worst code ever written but many people do. I have written a function with some mathematical derivatives to solve the problem in 2 lines of code.

            public static decimal RoundToPointFive(decimal value)
            {
                var intValue = ((int) value);
                return intValue + (Math.Round(value%intValue)*(decimal) 0.5);
            }

     
  2. Oct 18th, 2011     c math
blog comments powered by Disqus