将十进制值格式化为带有 2 个小数位的货币 [英] Format decimal value to currency with 2 decimal places

查看:34
本文介绍了将十进制值格式化为带有 2 个小数位的货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 csv 文件中获取数据并将其解析到我的应用程序中.在我的 csv 文件中,我有一个 price 列,我当然使用它的值作为项目中某个项目的价格.

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.

但是,csv 文件中的价格不包含尾随 0,例如,如果商品的价格为 $5.00,则 csv 文件将其设为 $5,如果商品的价格为 $9.60,则 csv 有它作为 $9.6.其他价格如 $9.56 也不错.

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.

这是我从 csv 文件中检索价格的方式:

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

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

在我的课上Price 被设置为公共十进制?价格{得到;放;}.

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.

如何修复它,以便将 csv 中的 $5.9 值格式化为 $5.90.

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

尝试过:

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

不确定我做对了吗?

另外,我不确定如何在我的代码中使用以下选项:

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

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

也试过了:

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

但是还是不行.

推荐答案

您正在寻找 "0:C2" 请参阅 标准数字格式字符串

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

精度说明符:小数位数

示例:

 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 个小数位的货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆