Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a number with commas, but keep decimals

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):

  • Please do not point me to this question it does not answer my question
  • Please do not point me to MSDN, the articles have not helped me. (If you believe I'm reading them incorrectly, read them yourself and post the correct answer)
  • .ToString("n") does not work, it rounds the digits
like image 793
Tom Ritter Avatar asked Nov 17 '08 15:11

Tom Ritter


People also ask

How do I change commas in Excel with decimals?

Click 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.

Do you put commas after a decimal?

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.

How do you use a comma and a dot in numbers?

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).


2 Answers

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
like image 122
James Curran Avatar answered Sep 22 '22 20:09

James Curran


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.#################")); 
}
like image 24
Rich Newman Avatar answered Sep 25 '22 20:09

Rich Newman