C#: Formatting Price value string

我们两清 提交于 2019-12-10 12:39:49

问题


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


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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

double price = 1234.25;
string FormattedPrice = price.ToString("N"); // 1,234.25



回答5:


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″ 



回答6:


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



来源:https://stackoverflow.com/questions/1142994/c-formatting-price-value-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!