Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding function to nearest 1/4

We only want to auto round the user entered values to the nearest .25 hour interval. So the user can enter 1.55 and it would round to 1.50 when saving to the database. If the user enters 1.90 to would save 2.00 to the database.

like image 231
Nayeem Mansoori Avatar asked Jan 15 '14 12:01

Nayeem Mansoori


People also ask

What does round to the nearest 1/4 mean?

When reporting time not worked, employees should round to the nearest 1/4 hour. For example: 15 minutes = 0.25 hours, 30 minutes = 0.50 hours and 45 minutes = 0.75 hours.

How do you round 4 or less?

For the digits five through nine, Round that number up the line. For the digits four and less, Round that number down, oh yes!


1 Answers

You can use Math.Round with MidpointRounding.AwayFromZero like;

double d = 1.55 * 4;
double i = Math.Round(d, MidpointRounding.AwayFromZero);
Console.WriteLine(i / 4);

Output will be

1.5

Here a demonstration.

As an explanation, multiplying 4 and then rounding gives you exactly 4 times with your decimal part like .00, .25, .50, .75.

Than dividing this double to 4, gives you exactly nearest .25 hour interval.

Here a full codes of examples;

double[] array = new[] { 1.0, 1.1, 1.2, 1.25, 1.3, 1.4, 1.5, 1.55, 1.6, 1.7, 1.75, 1.8, 1.9 };
foreach (double item in array)
{
    double d = item * 4;
    double i = Math.Round(d, MidpointRounding.AwayFromZero);
    Console.WriteLine(i / 4);
}

Output will be;

1.0 gives you 1.0
1.1 gives you 1.0
1.2 gives you 1.25
1.25 gives you 1.25
1.3 gives you 1.25
1.4 gives you 1.5
1.5 gives you 1.5
1.55 gives you 1.5
1.6 gives you 1.5
1.7 gives you 1.75
1.75 gives you 1.75
1.8 gives you 1.75
1.9 gives you 2.0

Here a full demonstration.

like image 111
Soner Gönül Avatar answered Sep 30 '22 05:09

Soner Gönül