String.Format in C# not returning modified int value

不羁岁月 提交于 2019-12-05 15:27:41

You shouldn't ToString the int before the format. Try this:

MessageBox.Show(string.Format("My number is {0:#,#}", myInt));

You are converting to string before the formatter has the chance to apply the formatting. You are looking for

MessageBox.Show(string.Format("My number is {0:#,#}", myInt));

myInt.ToString() is redundant since you are using a String.Format(). The point of String.Format is to supply is with a bunch of objects and it will create a string for you. No need to convert it to a string.

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 a string it doesn't take into account any numeric formatting since its already a string type.

int myInt = 1234567;
MessageBox.Show(string.Format("My number is {0:#,#}", myInt));

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:

int myInt = 1234567;
MessageBox.Show(string.Format("My number is {0:#,#}", myInt));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!