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?
似乎String.Format不会将字符串格式化为输入。我做错了什么,或者这只是本地行为?
Input : 0.37
输入:0.37
This doesn't work.
这不起作用。
string x = String.Format("{0:P}", myString)
Output : 0.37
产量:0.37
This does.
string x = String.Format("{0:P}", Convert.ToDecimal(myString))
Output : 37.00 %
产量:37.00%
3 个解决方案
#1
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.
有关更多信息,请参阅MSDN上的这篇文章。
#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.
您尝试应用的格式选项仅适用于数字。在.NET中没有智能字符串的概念,其中CLR检查字符串的类型。
#3
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!).
这是本机行为。解释字符串输入基本上不是Format的工作。格式假定用户提供正确的数据 - 在您的情况下,数字数据。字符串不是数字,即使它表示一个数字(这是值/语义与其表示/语法之间CS中最重要的区别!)。
#1
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.
有关更多信息,请参阅MSDN上的这篇文章。
#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.
您尝试应用的格式选项仅适用于数字。在.NET中没有智能字符串的概念,其中CLR检查字符串的类型。
#3
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!).
这是本机行为。解释字符串输入基本上不是Format的工作。格式假定用户提供正确的数据 - 在您的情况下,数字数据。字符串不是数字,即使它表示一个数字(这是值/语义与其表示/语法之间CS中最重要的区别!)。