Click here to Skip to main content
15,923,845 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I want to round off a number like for eg. if my value is 8.25 then automatically it be rounded up to 8.5 and if value is 8.75 then it should become 9
Posted
Comments
André Kraak 21-Sep-11 4:47am    
What should be the result for 8.15 and 8.65?
What ranges should be rounded to which decimal number?
Qureshali 21-Sep-11 5:24am    
My values will be either with .25 or .75

I don't think you really need rounding. It is rarely needed and can be dangerous. This is a typical situation.
Much more likely that you need a rounded string presentation of a number to show in UI, and this is completely different thing, which is really needed very often.

So, you need to use
string.Format<code> with appropriate format string.<br />
See:<br />
<a href="http://msdn.microsoft.com/en-us/library/system.string.format.aspx">http://msdn.microsoft.com/en-us/library/system.string.format.aspx</a>[<a href="http://msdn.microsoft.com/en-us/library/system.string.format.aspx" target="_blank" title="New Window">^</a>],<br />
<a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx">http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx</a>[<a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" target="_blank" title="New Window">^</a>],<br />
<a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx">http://msdn.microsoft.com/en-us/library/0c899ak8.aspx</a>[<a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx" target="_blank" title="New Window">^</a>].<br />
<br />
<dd>—SA</dd>
 
Share this answer
 
Check this code

C#
double f =8.25;
            double dresult;

            double dDecim = f - (int)f;
            if (dDecim > 0.5)
                dresult = Math.Round(f, 0);
            else
                dresult = Math.Round(f, 1);
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 21-Sep-11 20:54pm    
My answer may look a bit strange, but from my experience, people asking for rounding usually in fact need something different -- I answered accordingly, please see.
--SA
There is not any in-built function as you want
use Math.round function
C#
float tmp = 7.26;
float help = (float) Math.Round(tmp, 1);


and try to create your function using condition as per your requirement.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 21-Sep-11 20:55pm    
My answer may look a bit strange, but from my experience, people asking for rounding usually in fact need something different -- I answered accordingly, please see.
--SA

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