Reputation: 5043
I want to display a float as a string while making sure to display at least one decimal place. If there are more decimals I would like those displayed.
For example: 1 should be displayed as 1.0 1.2345 should display as 1.2345
Can someone help me with the format string?
Upvotes: 21
Views: 47066
Reputation: 17051
Try this:
doubleNumber.ToString("0.0###");
And, for your reference (double ToString method): http://msdn.microsoft.com/en-us/library/kfsatb94.aspx
Upvotes: 4
Reputation: 7505
This solution is similar to what other are saying, but I prefer to use string.Format. For example:
float myFloat1 = 1.4646573654;
float myFloat2 = 5;
Console.WriteLine(string.Format("Number 1 : {0:0.00##}", myFloat1));
Console.WriteLine(string.Format("Number 2 : {0:0.00##}", myFloat2));
// Newer Syntax
Console.WriteLine($"{myFloat1:0.00##}";
Console.WriteLine($"{myFloat2:0.00##}";
This would produce :
Number 1 : 1.4646
Number 2 : 5.00
Number 1 : 1.4646
Number 2 : 5.00
Upvotes: 14
Reputation: 21855
Use ToString(".0###########") with as much # as decimals you want.
Upvotes: 35
Reputation: 5253
float fNumber = 1.2345; // Your number
string sNumber = fNumber.ToString(); // Convert it to a string
If ((sNumber.Contains(".") == false) && (sNumber.Contains(",") == false)) // Check if it's got a point or a comma in it...
{
sNumber += ".0"; // ... and if not, it's an integer, so we'll add it ourselves.
}
Upvotes: 0