views:

110

answers:

2

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

+5  A: 

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.

Jay
Thanks, you may be right and I am thinking of the string version. My binding is one-way, but I'll let the question run for a while.
whybird
+1  A: 

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.

benPearce