Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

Float Variable format

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

Upvotes: 1

Views: 4142

Answers (3)

serhio
serhio

Reputation: 28586

?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"

Upvotes: 9

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

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");

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500505

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.

Upvotes: 2

Related Questions