3

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?

Vadim Kotov
  • 7,766
  • 8
  • 46
  • 61
Kahn Kah
  • 1,214
  • 7
  • 19
  • 45

2 Answers2

8

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;
Vadim Kotov
  • 7,766
  • 8
  • 46
  • 61
Markiian Benovskyi
  • 1,952
  • 20
  • 28
3

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.

Yves Daoust
  • 53,540
  • 8
  • 41
  • 94