Format decimal value to currency with 2 decimal places [duplicate]

你。 提交于 2019-12-13 12:00:17

问题


I am getting data from a csv file and parsing it to my application. In my csv file I have a column price whose value I use as of course the price of an item in my project.

However, the price in the csv file does not contain trailing 0s, For example, if the price of and item is $5.00, the csv file has it as $5, if the price is $9.60, the csv has it as $9.6. Other prices such as $9.56 are fine though.

This is how I retrieve the price from the csv file:

 Price = string.IsNullOrEmpty(columns[3].Trim()) ?
     null : (decimal?)decimal.Parse(columns[3]), 

In my class Price is set as public decimal? Price { get; set; }.

How do I format what is returned to fix this problem?

Price = String.Format("Price: {0:C}", 
     string.IsNullOrEmpty(columns[3].Trim()) ? 
        null : (decimal?)decimal.Parse(columns[3]));

I tried the above but didn't work.

How do I fix it so that values in the csv as $5.9 are formatted to $5.90.

EDIT:

Tried:

Price=decimal.Round(string.IsNullOrEmpty(columns[3].Trim()) ? 
    null : 
    (decimal?)decimal.Parse(columns[3]), 2, MidpointRounding.AwayFromZero);

Not sure if I did that right?

Also, I'm not certain how I can use the below option in my code:

decimalVar.ToString ("#.##");

Also tried:

 Price = string.IsNullOrEmpty(columns[3].Trim()) ? 
      null : (decimal?)decimal.Parse(columns[3], NumberStyles.Currency)

But still doesn't work.


回答1:


You are looking for "0:C2" see Standard Numeric Format Strings

Precision specifier: Number of decimal digits

Sample:

 String.Format("{0:C2}", 5d); //results in $5.00
 String.Format("{0:C2}", 5.9d); //results in $5.90
 String.Format("{0:C2}", 5.123d); //results in $5.12



回答2:


This answer is going to assume that your local currency symbol is $.

Use Decimal.Parse(String, NumberStyles) to parse the string, i.e:

string priceFromCsv = "$5";
var priceAsDecimal = Decimal.Parse(priceFromCsv, NumberStyles.Currency);

Then use Decimal.ToString(String) with the format "C" to get back to a fully formed currency, i.e.

priceAsDecimal.ToString("C");

This will give you the fully formed currency with the correct number of decimal places.




回答3:


decimals don't have a "format" - they are just a number. It looks like you're trying to "assign" a format to the Price column which you can't do. Based on your first code sample it seems that you're able to parse the CSV input to a decimal just fine.

You get to choose the format when you display the value, which you haven't indicated where that happens. In an app? a report? another CSV?



来源:https://stackoverflow.com/questions/21464496/format-decimal-value-to-currency-with-2-decimal-places

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