Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 763
whybird Avatar asked Sep 16 '10 03:09

whybird


1 Answers

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.

like image 132
Jay Avatar answered Nov 15 '22 13:11

Jay