I'd like to group the digits in a double by thousands, but also output however number of decimals are actually in the number. I cannot figure out the format string.
1000 => 1,000
100000 => 100,000
123.456 => 123.456
100000.21 => 100,000.21
100200.123456 => 100,200.123456
Disclaimers (it's not as straight forward as you think):
.ToString("n")
does not work, it rounds the digitsClick File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes. Tip: When you want to use the system separators again, select the Use system separators check box.
When a number uses a decimal point, we never place commas to the right of the decimal point. Some people like to use thin spaces going from left to right instead. Correct: The value of Pi is 3.14159 to five decimal places.
Using Commas in Numbers (US, UK, and China) In the US, UK, and China, a comma is placed every 3 decimal places for numbers larger than 999. The decimal point is shown with a period (full stop).
This appears to do exactly what you want:
public void Code(params string[] args)
{
Print(1000);
Print(100000);
Print(123.456);
Print(100000.21 );
Print(100200.123456);
}
void Print(double n)
{
Console.WriteLine("{0:###,###.#######}", n);
}
1,000
100,000
123.456
100,000.21
100,200.123456
An old thread, but none of the answers looks entirely satisfactory to me. Most of them turn zero into the empty string, including the one with the most upvotes.
I think a better solution is "#,##0.#################"
, which does at least show zeroes. It's still ugly though. There must be a better way.
double[] vals = new double[] { 0.0, 0.1234, -0.1234, 1.0,
123456789.123456, 123456789.0,
0.123456789123456 };
foreach (double val in vals)
{
Console.WriteLine(val + ": " + val.ToString("#,##0.#################"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With