Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

.net - C# MVC.Net format currency without decimals

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
[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 €");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...