开发者

Is there a way to make XAML / C# StringFormat show whole dollars for larger amounts but cents for smaller amounts?

In XAML, it is easy enough to use StringFormat='$#,0;$-#,0;Nil' to make a bound integer variable display as a nicely formatted dollar 开发者_高级运维amount. e.g., 1024 would come out as '$1,024'.

I have a need to deal with numbers ranging from a few cents up to a few hundred dollars - so 0.45 should display as '$0.45', but anything greater than some threshold (1? 9.99?) should display as a whole dollar amount. E.g. 12.73 should display as '$13'.

Before I go ahead and roll some moderately messy and specific code, does anyone have a nice clever way to do this? Ideally, it would all be in the StringFormat :)


I can't see how all this logic can be put in the StringFormat.

I think the cleanest way is an IValueConverter implementation. You can use a converter parameter to set the threshold, so that the converter can be reused and does not have a hard-coded value.

Unless you are using two-way binding, and if you are implementing MVVM, it is probably preferable to have a string variable in the view-model that returns the display value based on the integer value.


Don't be afraid of creating a Value Converter for this specific scenario.

If there is a business need for this type of formatting then it will quite likely be reused later anyway and making it a Value Converter makes it easier to reuse and test.

Jay's suggestion is probably as clean as it gets as your requirement will need to use logic for the formatting threshold.


try StringFormat='$ 0.##;#,$ #.##'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜