Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format Doesn't Format a String

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 %

like image 882
CodeMonkey1313 Avatar asked Apr 20 '09 18:04

CodeMonkey1313


3 Answers

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.

like image 125
Dan Esparza Avatar answered Nov 04 '22 07:11

Dan Esparza


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.

like image 45
Nick Berardi Avatar answered Nov 04 '22 06:11

Nick Berardi


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

like image 33
Konrad Rudolph Avatar answered Nov 04 '22 07:11

Konrad Rudolph