views:

163

answers:

3

I need to format float value and I only need 2 numbers after point and should be rounded value

 float first = 7, Second = 3,result;
 result = first / Second; // result contain 2.33333325 since I need like 2.33

Thanks

+4  A: 

You can round the number using Math.Round or specify how it should appear in output using format specifiers. If you want to do further calculations on the value you need to decide if you need the rounded value or the more accurate value.

For format specifiers you can use {0:f} in this case. See this post for examples http://blog.stevex.net/string-formatting-in-csharp/

Console.WriteLine(String.Format("{0:f}", result));

As Ben points out ToString accepts the same format specifiers, so if the number is not part of a text you can just do.

result.ToString("f");
Brian Rasmussen
Couldn't you also just use `result.ToString("f");` to use the standard numeric format strings? http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
Zhaph - Ben Duguid
Good point. I usually go with String.Format to include other text/numbers as well. I have added your comment to my answer. Thanks.
Brian Rasmussen
+5  A: 
?5/3
1.6666666666666667
?String.Format("{0:0.00}", 5/3)
"1,67"
?System.Math.Round(5/3, 2)
1.67

?(5.0 / 3).ToString("0.00")
"1,67"
?(5 / 3).ToString("0.00")
"1,00"
?(5.0 / 3).ToString("E") //Exponential
"1,666667E+000"
?(5.0 / 3).ToString("F") //Fixed-point
"1,67"
?(5.0 / 3).ToString("N") //Number
"1,67"
?(5.0 / 3).ToString("C") //Currency
"1,67 €"
?(5.0 / 3).ToString("G") //General
"1,66666666666667"
?(5.0 / 3).ToString("R") //Round-trip
"1,6666666666666667"
?(5.0 / 3).ToString("this is it .")
"this is it 2"
?(5.0 / 3).ToString("this is it .0")
"this is it 1,7"
?(5.0 / 3).ToString("this is it .0##")
"this is it 1,667"
?(5.0 / 3).ToString("this is it #####")
"this is it 2"
?(5.0 / 3).ToString("this is it .###")
"this is it 1,667"
serhio
thanks.........
Muhammad Akhtar
+1  A: 

As Brian says, floats are just stored as binary data - they don't contain a format. You may well want to only worry about this when you format the number as a string.

However, if you're interested in specific operations involving decimal points, you may want to look at using decimal instead of float to start with. What kind of numbers are you actually working with here?

In particular, if you're performing a number of operations and want to do rounding in the number itself then decimal is likely to be a better bet. See my articles on binary floating point and decimal floating point for more information.

Jon Skeet