Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to round the decimal value like this
if 5.50 => 5
if 5.51 => 6 ..
I want if the decimal value after point getter than .50 then the value increment by 1.
I used Math.Round() function, but it's round after .49 decimal value..
Posted
Updated 25-Jan-17 2:35am
Comments
Philippe Mori 25-Jan-17 12:40pm    
Using non standard rounding seems suspicious...

Use a custom rounding system:

C#
public int Round(double value)
{
    double decimalpoints = Math.Abs(value - Math.Floor(value));
    if (decimalpoints > 0.5)
        return (int)Math.Round(value);
    else
        return (int)Math.Floor(value);
}


Hope this helps. :-)
 
Share this answer
 
Comments
JayantaChatterjee 21-Feb-13 6:50am    
Thanks a lotttttttttttt Sir..
C#
public int myRound(double val)
{
    return (int)Math.Floor(val + .49);
}

I don't like "magic numbers" so you might want to define a const double and swap it for the 0.49
 
Share this answer
 
v2
Comments
JayantaChatterjee 21-Feb-13 6:55am    
I think This is more efficient then previous answers...
Thanks Sir....
Thanks a Lottttttttttt...:-)
Philippe Mori 25-Jan-17 12:39pm    
But it will not do the same thing for .495!
CHill60 27-Jan-17 10:50am    
I think your comment means that it won't work for values such as 5.501 for example. True, point well made. The solution is to use 0.499 as the magic number, or as many 9's as you suspect you will have digits after the decimal point. Not nice.
Although the OP stated they found my solution more efficient, Solution 3 is the better answer and works regardless of the mantissa.
kurt minds 29-May-18 10:53am    
use Format function. example Convert.toDouble(Format(5.4,"N0")) and it will return 6
CHill60 29-May-18 14:40pm    
Which isn't what the OP wanted and includes an unnecessary conversion to a string. I also don't like Convert functions
basic and simple way , you can convert decimal (5.50) to int (5) and you can check for 5.50-5 greater or lower than .50 if bigger then apply your algorithim..but i dont know any other function does that automaticly.
 
Share this answer
 
Comments
JayantaChatterjee 21-Feb-13 6:44am    
how to get after point(.) values?
boogac 21-Feb-13 6:47am    
decimal yourDecimal=5.50;
int temp = (int)yourDecimal;//or Convert.toInt32(..) 5.50 will be 5
decimal pointAfterDecimal= yourDecimal-(decimal)temp;
try,
String.Format("{0: 0}", _decimal_value);

hopes this work for you.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900