user2758530
user2758530

Reputation: 15

How to get the percentage of time in hours...?

I am developing a web application using asp.net c#. In that I need to get the percentage of Time. I am not getting the correct way to accomplish this. I have TotalHours which is coming from db. I need to calculate the 80% of that TotalHours.

Help will be appreciated. Thanks...

//This is how I am getting the TotalTime
TimeSpan TotalTime = TimeSpan.Parse(totalhours);

if(TotalTime != null)
{

TimeSpan Percentage= ( TotalTime* 80 ) / 100;
// here I need to get correct percentage in hrs
// If TotalTime is 10 hrs then Percentage should be 8 hrs 

}

Upvotes: 0

Views: 1316

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98750

TotalHours property of TimeSpan returns total number of hours as a double. That's why you can calcutate %80 of your TimeSpan like;

double Percentage = (TotalTime.TotalHours * 4) / 5;

Upvotes: 0

Chris Schubert
Chris Schubert

Reputation: 1298

TimeSpan TotalTime = TimeSpan.Parse("10:00:00");

if (TotalTime != null)
{
    var ticks = ((TotalTime.Ticks * 80) / 100);
    TimeSpan Percentage = new TimeSpan(ticks);
    Console.WriteLine(Percentage);  // 8 hours
}

Upvotes: 3

msmolcic
msmolcic

Reputation: 6557

TimeSpan totalTime = new TimeSpan(10, 0, 0);
TimeSpan percentage = TimeSpan.FromMilliseconds((totalTime.TotalMilliseconds * 80) / 100);

Get total miliseconds from your totalTime, do the math and convert it back to TimeSpan from miliseconds.

If you're satisfied with hours simply change:

TimeSpan percentage = TimeSpan.FromHours((totalTime.TotalHours * 80) / 100);

Upvotes: 2

Related Questions