String.Format Doesn't Format a String
Asked Answered
I

3

6

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 %

Injection answered 20/4, 2009 at 18:44 Comment(0)
H
9

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.

Haroldharolda answered 20/4, 2009 at 18:48 Comment(0)
A
2

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.

Aulea answered 20/4, 2009 at 18:48 Comment(0)
U
2

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

Uzziel answered 20/4, 2009 at 18:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.