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
2009-07-17 12:34:16
I don't think they wanted a currency symbol.
Andrew Hare
2009-07-17 12:36:53
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
2009-07-17 12:37:08
+4
A:
Look into format strings, specifically "C" or "N".
double price = 1234.25;
string FormattedPrice = price.ToString("N"); // 1,234.25
Joel Coehoorn
2009-07-17 12:34:45
+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
2009-07-17 12:35:31
Isn't 2 kind of default though? So that you would just need `myPrice.ToString("N")`? Not important, just curious :p
Svish
2010-01-06 12:48:58
+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
2009-07-17 12:42:35
Indeed.Decimals should be used for things where precision matters.
Frederik Gheysels
2009-07-17 12:45:30
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
2009-07-17 13:41:20
+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
2010-01-06 12:42:45