String.Format does not format the string

It seems that String.Format will not format the string as input. Am I doing something wrong, or is this just normal behavior?

Entrance: 0.37

This does not work.

string x = String.Format("{0:P}", myString) 

Output: 0.37

It does.

 string x = String.Format("{0:P}", Convert.ToDecimal(myString)) 

Yield: 37.00%

+6
string.format
source share
3 answers

I believe this is the expected behavior for "composite formatting."

In the first example, we are trying to apply numerical formatting rules to a string. A second example is to apply numerical formatting rules to a number that can have decimal positions.

For more information, see this article on MSDN .

+9
source share

The format option you are trying to apply only works for numbers. In .NET, there is no concept of smart strings in which the common language runtime checks the string for a type.

+2
source share

Am I doing something wrong, or is this just native behavior?

This is native behavior. Basically this is not a Format job to interpret string input. Format assumes that the user is supplying the correct data - in your case - numeric data. A string is not numeric even if it represents a number (this is an important difference in CS between a value / semantics and its representation / syntax!).

+2
source share

All Articles