I want to be rounded off this way
13.1, round to 13.5
13.2, round to 13.5
13.3, round to 13.5
13.4, round to 13.5
13.5 = 13.5
13.6, round to 14.0
13.7, roun
This works, I just tested it;
double a = 13.3;
var rn = a % 0.5 == 0 ? 1 : 0;
Math.Round(a, rn);
A simple way of doing this without the builtin method of c# (if you want ) its writen i c++ (I once lacked the round function in c++ ) but you can easly change it to c# syntax
int round(float nNumToRound)
{
// Variable definition
int nResult;
// Check if the number is negetive
if (nNumToRound > 0)
{
// its positive, use floor.
nResult = floor(nNumToRound + 0.5);
}
else if (nNumToRound < 0)
{
// its negtive, use ceil
nResult = ceil(nNumToRound - 0.5);
}
return (nResult);
}
Nearest 0.5
for 13.6
and 13.7
is 13.5
, so you have correct solution.
for yours table of values:
var value = 13.5;
var reminder = value % (int)value;
var isMiddle = Math.Abs(reminder - 0.5) < 0.001;
var result = (isMiddle ? Math.Round(value * 2, MidpointRounding.AwayFromZero): Math.Round(value)*2)/ 2;
var a = d == (((int)d)+0.5) ? d : Math.Round(d);
d is a double.
If it is required for 13.1, round to 13.5
and 13.9, round to 14.0
, then:
double a = 13.1;
double rounded = Math.Ceil(a * 2) / 2;
num = (num % 0.5 == 0 ? num : Math.Round(num));
works well for you solution heres the complete console program
static void Main(string[] args)
{
double[] a = new double[]{
13.1,13.2,13.3D,13.4,13.5,13.6,13.7,13.8,13.9,13.58,13.49,13.55,
};
foreach (var b in a)
{
Console.WriteLine("{0}-{1}",b,b % 0.5 == 0 ? b : Math.Round(b));
}
Console.ReadKey();
}
you simply would need to change 0.5
to some other number if the rounding requirement changes in future