tags:

views:

193

answers:

5

I have a number with a variable number of digits after the decimal point. I want to format the number with commas and all decimal numbers.

For example: 42,023,212.0092343234

If I use ToString("N") I get only 2 decimals, ToString("f") gives me all decimals no commas. How do I get both?

A: 

Try ToString("N2")

Akash Kava
That only displays the last 2 decimals, I want it to display all of them but the number of decimals will vary from 0-?
NotDan
+1  A: 

UPDATE: Looking at the MSDN documentation on the System.Double type, I see this:

By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally.

So I think pdr's on to something, actually. Just do this:

// As long as you've got at least 15 #s after the decimal point,
// you should be good.
value.ToString("#,#.###############");

Here's an idea:

static string Format(double value)
{
    double wholePart = Math.Truncate(value);
    double decimalPart = Math.Abs(value - wholePart);
    return wholePart.ToString("N0") + decimalPart.ToString().TrimStart('0');
}

Example:

Console.WriteLine(Format(42023212.0092343234));

Output:

42,023,212.00923432409763336

Ha, well, as you can see, this gives imperfect results, due (I think) to floating point math issues. Oh well; it's an option, anyway.

Dan Tao
That would probably work, but I'd like to get a format string that I can give to a Grid Control, or anything else that understands .Net formatting so it can do the formatting for me and I can just give it the actual value.
NotDan
+4  A: 

Not sure (and unable to test right now) but would something like this work?

"#,##0.################"
pdr
Best so far, it works as long as the decimals aren't longer than the number of #'s... I was hoping to avoid this option but if its the only way.....
NotDan
Good call. I say this is the best answer.
Dan Tao
+1  A: 
string.Format("{0:#,##0.############}", value);

will give you up to 12 decimal places.

There is not a custom format specifier for "all following digits", so something like this will be closest to what you want.

Note too that you're limited by the precision of your variable. A double only has 15-16 digits of precision, so as your left-hand side gets bigger the number of decimal places will fall off.

GalacticCowboy
A: 

Here is the way somewhat to reach to your expectation...

decimal d = 42023212.0092343234M;

NumberFormatInfo nfi  = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone();

nfi.NumberDecimalDigits= (d - Decimal.Truncate(d)).ToString().Length-2;

Console.WriteLine(d.ToString("N",nfi));

For more detail about NumberFormatInfo.. look at MSDN ..

http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx

Jeeva S
can somebody tell me the reason for downvote?
Jeeva S
Probably because you're doing a double-cast to string.
Josh Stodola