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
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));
精彩评论