没有小数C#MVC.Net格式货币 [英] C# MVC.Net format currency without decimals

查看:166
本文介绍了没有小数C#MVC.Net格式货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一个DataFormatString,将显示一个浮动的货币。但省略了十进制值,如果他们不相关(0)。

目前我使用的那一刻:

  [DisplayFormat(DataFormatString ={0:C})]
 

在我的模型。这是正确显示为货币。我一直没能找到任何地方,详细说明什么样的变化,我需要做省略小数点?

解决方案

  [DisplayFormat(DataFormatString ={0:C0})]
 

这应该给你0小数。但是,自动轮!所以,如果你得到了,56将四舍五入到1

20000,00 => 20000€

20000,56 => 20001€

20000,49 => 20000€

/编辑:我借用一个想法从这里: C#十进制转换为字符串货币

如果您可以将您的浮点值转换为十进制,你可以使用这个Extensionmethod省略0。截断小数,如果这截断值等于原来的值,它减少了零。如果没有,则显示2位数字。 我知道这是没有DATAFORMAT字符串,但我不安静肯定的是,它可以在一个简单的方式注解来完成。

 公共静态字符串ToCurrencyString(此十进制D)
{
    返回d.Equals(Decimal.Truncate(D))? d.ToString(0€):d.ToString(0.00€);
}
 

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).

At the moment I'm using:

[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}")]

This should give you 0 decimals. But automatically rounds! so if you got ,56 it will round up to 1

20000,00 => 20000 €

20000,56 => 20001 €

20000,49 => 20000 €

/edit: I have borrowed an idea from here: c# Decimal to string for currency

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

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