Reputation: 3
I haven't seen an example of combining these 2 concepts.
What if I want to show that same number in thousands And with comma separators (e.g. 1,833) ?
I'm sure there's ways to do it using formulas/calculations. But I'd like to know if there's a direct way with a format string ?
Thanks.
Upvotes: 0
Views: 128
Reputation: 216293
This format will do what you have requested
"#,##0,"
as in
Console.WriteLine(1832567.ToString("#,##0,"));
You can see an example at https://dotnetfiddle.net/leoOnc
This seems to be described here at Custom Numeric Format Strings in the section dedicated to the The "," custom format specifier where they talk about how the comma could be used for both
Group separator: If one or more commas are specified between two digit placeholders (0 or #) that format the integral digits of a number, a group separator character is inserted between each number group in the integral part of the output.
...
Number scaling specifier: If one or more commas are specified immediately to the left of the explicit or implicit decimal point, the number to be formatted is divided by 1000 for each comma. For example, if the string "0,," is used to format the number 100 million, the output is "100".
Upvotes: 1
Reputation: 415735
You can divide by 1000.0 and the first format string will remove the extra characters:
int foo = 1832567;
Console.WriteLine( (foo/1000.0).ToString("#,##0"));
But that fails the "within a format string" part of the request. Maybe this can still qualify as part of an interpolated string, since we can fit everything between the curly braces:
int foo = 1832567;
Console.WriteLine($"{foo/1000.0:#,##0}");
Note the .0
to avoid integer division, which would truncate rather than round the result.
Upvotes: 1