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

馋奶兔 提交于 2019-12-04 03:08:27

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

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.

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?

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