Click here to Skip to main content
15,913,115 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello Everybody

I need to round a double value with two decimal places.

What I need to do that.

for example

x=7.3256

I need convert x in x=7.33

How I can do that in c# code.

Thanks in advance
Posted

This should do the trick:
C#
x = Math.Round(x, 2);
 
Share this answer
 
v2
Comments
Espen Harlinn 4-Jan-11 11:25am    
+5 Simplicity--the art of maximizing the amount of work not done--is essential.
#realJSOP 4-Jan-11 11:32am    
Yep, I wasn't aware that Math.Round had that overload until I started playing with it. I came back here to modify my answer, but instead, deleted it because you already posted the right answer.
wizardzz 4-Jan-11 12:51pm    
I live by this function.
Sergey Alexandrovich Kryukov 4-Jan-11 15:14pm    
@JF2015:

I'll vote 5 in hope you read my answer and improve yours by a proper comment.
I did not want to down-vote your answer only because you answer literally.

Nevertheless my point is not answering but helping people even they do not know how to ask correctly (way too typical).

Caution! Are you sure you need rounding?



Chances are, you don't need rounding at all.

Rounding per se should almost never be used (exclusions are rare and very advanced: in random number generation, cryptography...). Most probably, you only need rounded look of the figures when converted to string for output. In practice, this is different. All you need is proper string formatting:

C#
System.Console.WriteLine("{0:G3}", myDoublePrecisionNumber);

or
C#
string output = 
   string.Format("{0:G3}", myDoublePrecisionNumber);


For further help, type string.Format, press F1 on Format and read Microsoft help -- all you need.
Don't mess with rounding unless it is really needed.
 
Share this answer
 
v2
Comments
#realJSOP 4-Jan-11 15:18pm    
He may not need the value to be displayed, so converting it to a string would be a waste of cycles. JF2015's answer is correct.
Sergey Alexandrovich Kryukov 4-Jan-11 17:38pm    
John, you may be missed my point.

Formally, JF2015's answer is correct. But who really needs rounding? (Well, I listed some cases.)
It is not likely at all. Most likely, the question was not formulated correctly; and correct question would be exactly about formatting.

Your comment "converting it to a string would be a waste of cycles" misses the target. Of course it would! I never proposed the converting. A proposed to not to address rounding -- I'm almost sure it is irrelevant.

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