Question

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.

Was it helpful?

Solution 3

0.25 is 1/4, so you can get it easily by

double rounded = round(4.0 * hoursEntered) / 4.0

round does not exist. You must use appropriate rounding function and options. For aspx.cs (C# codebehind) see System.Math.Round.

Also, to link it to the textbox on the webpage, you will need some rule/validator or textchange handler or anywhere around the typical text parsing. You may also try doing it in JavaScript client side, the *4/4 trick stays the same, just round function will have different name.

OTHER TIPS

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.

Something like this should do it:

double value = 1.55;    
double roundedValue = Math.Round(value/.25)*.25;

You could use the ToInt32() conversion function as follows:

double x = input_value;
x = x * 4;
int y = Toint32(x);
x = ((double) y) / 4;

I think that would work. I see that there are other more elegant solutions, though.

The Math.Round method is called several times. Because the .NET Framework differentiates between a decimal type and a double type, the best overloads are automatically chosen. You can call Math.Round with one to three arguments. Read this article

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