C# 中的 String.Format 不返回修改后的 int 值
我试图返回一个 int 值,该值内带有逗号分隔符。
12345 将返回为 12,345
以下代码有效:
int myInt = 1234567;
MessageBox.Show(string.Format("My number is {0}", myInt.ToString("#,#")));
12,345 按预期显示。
虽然以下代码不起作用,但从我正在阅读的内容来看,应该可以工作:
int myInt = 1234567;
MessageBox.Show(string.Format("My number is {0:#,#}", myInt.ToString()));
显示 12345。
您能帮我理解为什么第二组代码不起作用吗?
谢谢
I am tring to return an int value with comma seperators within the value.
12345 would be returned as 12,345
The follwing code works:
int myInt = 1234567;
MessageBox.Show(string.Format("My number is {0}", myInt.ToString("#,#")));
12,345 is displayed as expected.
While the following code does no work, but from what I am reading, should work:
int myInt = 1234567;
MessageBox.Show(string.Format("My number is {0:#,#}", myInt.ToString()));
12345 is displayed.
Can you help me understand why the second set of code is not working?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不应该在格式之前
ToString
int。试试这个:You shouldn't
ToString
the int before the format. Try this:在格式化程序有机会应用格式之前,您将转换为字符串。您正在寻找
You are converting to string before the formatter has the chance to apply the formatting. You are looking for
myInt.ToString()
是多余的,因为您使用的是String.Format()
。String.Format
的要点是提供一堆对象,它会为您创建一个字符串。无需将其转换为字符串
。为了反映数字格式,您需要为其提供实际的数值类型,而不是
string
类型的数值。当您为
Format
方法提供一个string
时,它不会考虑任何数字格式,因为它已经是string
类型。myInt.ToString()
is redundant since you are using aString.Format()
. The point ofString.Format
is to supply is with a bunch of objects and it will create a string for you. No need to convert it to astring
.In order for the Numeric Format to reflect you need to give it an actual numeric value type not a numeric value that's of type
string
.When you give the
Format
method astring
it doesn't take into account any numeric formatting since its already astring
type.当您像第二个示例中那样使用“内联”格式字符串时,参数的输入需要是原始值(即 int、double 或其他值),以便格式字符串可以用它做一些有用的事情。
因此,从第二次调用中省略 ToString 将执行您想要的操作:
When you use format strings "inline" as in your second example, the input to the parameter needs to be the original value (i.e int, double, or whatever) so that the format string can do something useful with it.
So omitting the ToString from the second call will do what you want: