Reputation: 163
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, round to 14.0
13.8, round to 14.0
13.9, round to 14.0
sorry for modification i need in the above way... did this way but not appropriate
doubleValue = Math.Round((doubleValue * 2), MidpointRounding.ToEven) / 2;
Upvotes: 4
Views: 10794
Reputation: 18071
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;
Upvotes: 9
Reputation: 8706
I don't know if it is proper way, but it works. Try this if you want:
double doubleValue = 13.5;
double roundedValue = 0.0;
if (doubleValue.ToString().Contains('.'))
{
string s = doubleValue.ToString().Substring(doubleValue.ToString().IndexOf('.') + 1);
if (Convert.ToInt32(s) == 5)
{
roundedValue = doubleValue;
}
else
{
roundedValue = Math.Round(doubleValue);
}
}
Console.WriteLine("Result: {0}", roundedValue);
Upvotes: 0
Reputation: 5503
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;
Upvotes: 0
Reputation: 12705
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
Upvotes: 0
Reputation: 4816
This works, I just tested it;
double a = 13.3;
var rn = a % 0.5 == 0 ? 1 : 0;
Math.Round(a, rn);
Upvotes: 1
Reputation: 5133
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);
}
Upvotes: 0