Kahn Kah
Kahn Kah

Reputation: 1453

Minutes to hours in decimal + round in C#

I'm trying to convert minutes to hours in decimal and round to the nearest fifteen minutes (rounded up).

Basically:

15 minutes = 0.25 hour

25 minutes = 0.5 hour

30 minutes = 0.5 hour

50 minutes = 1 hour

60 minutes = 1 hour

I haven't found anything relevant here on stackoverflow but another website tells me to:

var hours =  Math.Round((minutes * 100 ) / 60.0);

Which doesn't come near to the result.

I know I can't use Math.Round() (because it casts it to an int?). Same for TimeSpan (because it gives .TotalHours in a double).

What can a good approach be starting with dividing it by 60?

Upvotes: 3

Views: 3508

Answers (2)

Markiian Benovskyi
Markiian Benovskyi

Reputation: 2161

Lets think that you have minutes and want to convert them to hours (0.25, 0.5, 0.75, 1)

First we get what quarter it is: Math.Ceiling(minutes / 15.0)

Math.Ceiling returns you 4 if you have 3.01

And then just divide it by 4 to have quarters

var hours = Math.Ceiling(minutes / 15.0)/4.0;

Upvotes: 8

user1196549
user1196549

Reputation:

Use one of

  • Math.Round(minutes / 15) * 0.25,
  • Math.Floor(minutes / 15) * 0.25 or
  • Math.Ceiling(minutes / 15) * 0.25

depending on the exact rounding you want (nearest, down or up).

minutes / 15 tells you a number of quarters, which you round, then 0.25 converts to hours.

Upvotes: 3

Related Questions