如何将小数属性格式化为货币?
我想将小数值格式化为货币值。
我该怎么做?
I want to format a decimal value as a currency value.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我想将小数值格式化为货币值。
我该怎么做?
I want to format a decimal value as a currency value.
How can I do this?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(9)
属性可以返回它们想要的任何内容,但需要返回正确的类型。
有人问...如果它是一个可为空的小数怎么办?
Properties can return anything they want to, but it's going to need to return the correct type.
Question was asked... what if it was a nullable decimal.
下面也可以,但是你不能放入小数属性的 getter。小数属性的 getter 只能返回小数,格式不适用。
Below would also work, but you cannot put in the getter of a decimal property. The getter of a decimal property can only return a decimal, for which formatting does not apply.
试试这个;
它将把 123423.083234 转换为 $1,23,423 格式。
Try this;
It will convert 123423.083234 to $1,23,423 format.
您可以创建一个扩展方法。我发现这是一个很好的做法,因为无论浏览器设置如何,您都可能需要锁定货币显示。例如,您可能希望始终显示 $5,000.00 而不是 5 000,00 $
(#加拿大问题)
You can create an extension method. I find this to be a good practice as you may need to lock down a currency display regardless of the browser setting. For instance you may want to display $5,000.00 always instead of 5 000,00 $
(#CanadaProblems)
您可以使用 String.Format,请参阅代码 [via How-to Geek]:
另请参阅:
You can use String.Format, see the code [via How-to Geek]:
See also:
您现在可以在 C# 6 中使用字符串插值和表达式主体属性。
You can now use string interpolation and expression bodied properties in C# 6.
您的返回格式将受到您声明的返回类型的限制。所以是的,您可以将属性声明为字符串并返回某些内容的格式化值。在“get”中,您可以放置您需要的任何数据检索代码。因此,如果您需要访问某些数值,只需将 return 语句写为:
Your returned format will be limited by the return type you declare. So yes, you can declare the property as a string and return the formatted value of something. In the "get" you can put whatever data retrieval code you need. So if you need to access some numeric value, simply put your return statement as:
小数类型不能包含格式信息。您可以创建另一个属性,例如可以执行您想要的操作的字符串类型的
FormattedProperty
。A decimal type can not contain formatting information. You can create another property, say
FormattedProperty
of a string type that does what you want.就我而言,我必须将其转换为十进制,如上所述,我使用字符串格式方法,然后将其解析为十进制,它对我来说效果很好,这里是示例。
publicdecimalAmount;
publicdecimal_amount;
所以我分配了这样的值:
Amount =decimal.Parse(String.Format("{0:C}", _amount ))
In My case, I have to convert it into decimal as above mentioned I used to string Format method and then parse it to decimal and it works fine for me here is the example.
public decimal Amount;
public decimal_amount;
So I assigned values like this:
Amount = decimal.Parse(String.Format("{0:C}", _amount))