Reputation: 16011
It seems as though String.Format won't format a string as an input. Am I doing something wrong, or is this just native behavior?
Input : 0.37
This doesn't work.
string x = String.Format("{0:P}", myString)
Output : 0.37
This does.
string x = String.Format("{0:P}", Convert.ToDecimal(myString))
Output : 37.00 %
Upvotes: 6
Views: 2531
Reputation: 545488
Am I doing something wrong, or is this just native behavior?
That's native behaviour. It's basically not the job of Format
to interpret string input. Format
assumes that the user supplies the right data – in your case, numeric data. A string isn't numeric, even if it represents a number (this is the all-important distinction in CS between a value/semantics and its representation/syntax!).
Upvotes: 2
Reputation: 54854
The format option you are trying to apply only works for numbers. There is no concept of smart strings in .NET in which the CLR inspects the string for a type.
Upvotes: 2
Reputation: 28367
I believe this is expected behavior for 'composite formatting'.
Your first example is attempting to apply numerical formatting rules to a string. Your second example is attempting to apply numerical formatting rules to a number that can have decimal positions.
See this article on MSDN for more information.
Upvotes: 9