C# MVC.Net 格式货币不带小数

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

问题描述

我正在寻找将浮点数显示为货币的 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 格式货币不带小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)