How to Round to the Nearest 0.5?
.net, c#
Solution
This extension method ought to do the job:
public decimal RoundToNearestHalf(this decimal value)
{
return Math.Round(value * 2) / 2;
}
var num1 = (3.7).RoundToNearestHalf(); // 3.5
var num1 = (4.0).RoundToNearestHalf(); // 4.0
I've used the `decimal` type in the code because it seems you want to maintain base 10 precision. If you don't, then `float`/`double` would do just as well, of course.
Problem
in my application Ex 1: Start time 12.30 (-)End time 16.00 here i get the value as 3.7 but i need to show this 3.7 as 3.5 in my application Ex 2: Start time 12.00 (-)End time 16.00 here i get the value as 4.0 here there is no need to alter the value (1.7,2.7,3.7,4.7,.... etc ) as to be represented as(1.5,2.5,3.5,4.5,.. etc ) so how to write an function for this where if the vale contains(1.7,2.7) i should change to 1.5,2.5 or if it contains 1.0,2.0 then there is no need to replace any value?