Reputation: 218852
in C#,I have a double variable price with value 10215.24. I want to show the price with comma after some digits. My expected output is 10,215.24
Upvotes: 17
Views: 48507
Reputation: 11016
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″
Upvotes: 3
Reputation: 56954
myPrice.ToString("N2");
depending on what you want, you may also wish to display the currency symbol:
myPrice.ToString("C2");
(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.
Upvotes: 36
Reputation: 9072
The one you want is "N2".
Here is an example:
double dPrice = 29.999988887777666655554444333322221111;
string sPrice = "£" + dPrice.ToString("N2");
You might even like this:
string sPrice = "";
if(dPrice < 1)
{
sPrice = ((int)(dPrice * 100)) + "p";
} else
{
sPrice = "£" + dPrice.ToString("N2");
}
which condenses nicely to this:
string sPrice = dPrice < 1 ? ((int)(dPrice * 100)).ToString("N0") + "p" : "£" + dPrice.ToString("N2");
Further reading at msdn.microsoft.com/en-us/library/fht0f5be.aspx for various other types of formatting
Upvotes: 0
Reputation: 19620
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.
Upvotes: 6
Reputation: 416059
Look into format strings, specifically "C" or "N".
double price = 1234.25;
string FormattedPrice = price.ToString("N"); // 1,234.25
Upvotes: 5
Reputation: 60518
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);
Upvotes: 21