Question

I have a user input values in my table. Here if user enters 3.2, it mean 3 hours and 20 min.

I am showing the total hours that has been input by the user in the entire week.

Inputs are:
Sun : 3.2
Mon : 4.5
Tue: 5.0

Now, 3.2 + 4.5 + 5.0 = 12.70 which would mean 12 hours and 70 min. However, I want the result to be 13.10 (which is 13 hours and 10 min) instead of 12.70.

I need the total in a select query which is binding my grid with the rest of the data.

Currently i am using the sum function in the select query along with other columns.

How do I do this?

No correct solution

OTHER TIPS

Your input format won't work at all.

You are lucky it does in your example but in most cases it just won't. For instance, if 2 persons input "1 hour and 50 minutes" :

1.5 + 1.5 = 3.0

You cannot read it as : "three hours" since in reality it is "3 hours and 40 minutes".

As soon as the sum of "minutes" is greater thant 0.99, your are wrong.


But in the few lucky cases, you can do some arithmetic (if you want a result in the same "double" format as your input)?

var inputList = new List<double>() {3.2, 4.5, 5.0};
double total = inputList.Sum();

int baseHours = (int)Math.Floor(total);
int realBaseHours = (int)inputList.Sum(d => Math.Floor(d));

if (baseHours > realBaseHours)
    throw new Exception("All hell breaks loose!");

int baseMinutes = (int)(total * 100.0 - baseHours * 100.0);

int finalHours = baseHours + baseMinutes / 60;
int finalMinutes = baseMinutes % 60;

double result = finalHours + finalMinutes / 100.0;

It's not good to saving times as a double format, but for your question:

Get all times as array of double values and do some arithmetic:

double[] times = { 3.2, 4.5, 5.0 };
int hours = 0;
int minuts = 0;
string[] values;
foreach (double t in times)
{
  values = t.ToString("#.00").Split('.');
  hours += int.Parse(values[0]);
  minuts += int.Parse(values[1]);
}
hours += minuts / 60;
minuts += minuts % 60;

It work for all kind of times as double format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top