问题描述
我正在寻找将浮点数显示为货币的 DataFormatString.但如果它们不相关(0),则忽略十进制值.
I'm looking for a DataFormatString that will display a float as a currency. But omit the decimal values if they're irrelevant (0's).
目前我正在使用:
[DisplayFormat(DataFormatString = "{0:C}")]
在我的模型上.这正确显示为货币.我找不到任何地方详细说明我需要进行哪些更改才能省略小数位?
On my models. This is displaying as a currency correctly. I've not been able to find anywhere that details what changes I need to make to omit the decimal places?
推荐答案
[DisplayFormat(DataFormatString = "{0:C0}")]
这应该给你 0 位小数.但自动轮回!因此,如果您得到 ,56,它将向上取整为 1
This should give you 0 decimals. But automatically rounds! so if you got ,56 it will round up to 1
20000,00 => 20000 欧元
20000,00 => 20000
20000,56 => 20001 欧元
20000,56 => 20001
20000,49 => 20000 欧元
20000,49 => 20000
/edit:我从这里借用了一个想法:c# Decimal to string货币
/edit: I have borrowed an idea from here: c# Decimal to string for currency
如果您可以将浮点值转换为十进制,则可以使用此扩展方法省略 0.它会截断小数,如果此截断值等于原始值,则会截断零.如果不是,则显示 2 位数字.我知道这不是 Dataformat 字符串,但我不确定,它可以像注释一样简单地完成.
If you can convert your float value to decimal, you can use this Extensionmethod to omit the 0. It truncates the decimal and if this truncated value is equal to the original value, it cuts the zeros. If not, it displays 2 digits. I know this is no Dataformat string, but I'm not quiet sure, it can be done in an as simple way as an annotation.
public static string ToCurrencyString(this decimal d)
{
return d.Equals(Decimal.Truncate(d)) ? d.ToString("0 ") : d.ToString("0.00 ");
}
这篇关于C# MVC.Net 格式货币不带小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!