Reputation: 3993
Is that possible in C# to format
4.52
float number to 4.52
string
and
4.520
float number to 4.52
string, i.e. omitting tail zeros?
EDIT: I think I've not accented the real problem. I need ONE pattern that conforms BOTH of the above examples!
Upvotes: 2
Views: 4511
Reputation: 1857
Actually, you don't need a pattern. .NET always omits the tail zeros of float numbers, unless specified to do not.
So Console.WriteLine(4.520)
would output 4.52
, as would Console.WriteLine(4.52)
or Console.WriteLine(4.520000000000)
, as Console.WriteLine(4.5)
would output 4.5
.
In the example above, the System.Console.WriteLine
method will internally call ToString()
(with no patterns) on your float number.
Also, if you're looking for something more specific, you can take a look at
http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.71).aspx
for some more number format strings.
Upvotes: 2
Reputation: 7546
All of these result in "4.52":
string formatted = 4.52.ToString();
string formatted = 4.520.ToString();
Because that was too easy I wonder if maybe your float is really a string:
string formatted = "4.52".Trim('0');
string formatted = "4.520".Trim('0');
Upvotes: 0
Reputation: 82096
Assuming you want to omit any trailing 0's from your value, this should give you what you want:
ToString("0.####")
Otherwise you could do:
ToString("0.00##")
Upvotes: 7