views:

440

answers:

3

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 %

+8  A: 

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.

Dan Esparza
+2  A: 

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.

Nick Berardi
+2  A: 

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!).

Konrad Rudolph