views:

385

answers:

5

in C#,I have a double variable price with value 10215.24. I want to show the price with comma after some digits.Can anyone help me to do this.My expected output is 10,215.24

+8  A: 

I think this should do it:

String.Format("{0:C}", doubleVar);

If you don't want the currency symbol, then just do this:

String.Format("{0:N2}", doubleVar);
Eric Petroelje
I don't think they wanted a currency symbol.
Andrew Hare
this answer is spot on. However, also have a look at http://msdn.microsoft.com/en-us/library/fht0f5be.aspx for various other types of formatting.
James
+4  A: 

Look into format strings, specifically "C" or "N".

double price = 1234.25;
string FormattedPrice = price.ToString("N"); // 1,234.25
Joel Coehoorn
+7  A: 
myPrice.ToString("C2");

or

myPrice.ToString("N2");

depending on what you want. (The number after the C or N indicates how many decimals should be used). (C formats the number as a currency string, which includes a currency symbol)

To be completely politically correct, you can also specify the CultureInfo that should be used.

Frederik Gheysels
I think that "N2" is what they are after.
Andrew Hare
Isn't 2 kind of default though? So that you would just need `myPrice.ToString("N")`? Not important, just curious :p
Svish
+4  A: 

As a side note, I would recommend looking into the Decimal type for currency. It avoids the rounding errors that plague floats, but unlike Integer, it can have digits after the decimal point.

Steven Sudit
Indeed.Decimals should be used for things where precision matters.
Frederik Gheysels
In certain financial applications, it's flatly illegal to use floats because all rounding must be done in a prescribed manner. The alternative where a Decimal or BigNumbers type of class is unavailable is to use integers to store fractions of a currency unit. So, for example, we could count pennies or fractions thereof.
Steven Sudit
+1  A: 

This might help

    String.Format("{#,##0.00}", 1243.50); // Outputs “1,243.50″

    String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, 1243.50); // Outputs “$1,243.50″ 

    String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, -1243.50); // Outputs “($1,243.50)″ 

    String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, 0); // Outputs “Zero″ 
Thunder