IMPORTANT NOTE: consider this a general answer. The specific UI framework you're using leads to what's the best practice to use. If, for example, this is a WPF application then you just need a plain ValueConverter
and no properties in your View Model (again...assuming this is your VM).
First of all casting to double
you're introducing errors, the same errors you're trying to avoid storing pennies in an int
field. Use decimal
instead (and consider to use Money
- or whatever else your DBE has - inside the database).
I, personally, find extremely confusing to have a property Cost
expressed in pennies. You may change the name to make it explicit (something like CostInPennies
) or drop it and convert it to/from decimal
when you read/write to/from DB (and the unadjusted value).
What's better between alternatives you've proposed? What's the benefit of the first? It's small and it keeps the logic in the right place. I'd rewrite it to be more concise:
public string DisplayCost => Convert.ToString(Cost / 100.0m);
The second one, however, has a great benefit if your object is observable: updating the DisplayCost
property keeps the INotifyPropertyChanged
stuff inside the DisplayCost
setter leading to much cleaner code. If you don't implement INotifyPropertyChanged
(or similar) then I'd go with the first one (and I'd not even bother to store the value somewhere, just recalculate it when required).
In any case I'd introduce a simple helper method to perform this formatting (there are good chances it's reused elsewhere), something like:
static class MoneyFormatter {
public static string PenniesToString(int pennies)
=> Convert.ToString(pennies / 100.0m);
}
You can then test its logic without any Item
's implementation detail. In future you may need to handle something else and it's then better to have everything in one place. Don't forget:
- Thousands separator: it is probably helpful to quickly scan a column of numbers.
- Rounding: you don't always need precision to one penny, in some circumstances (for example a dashboard) you MAY even round (for example 10,123$ might be displayed as 10k).
- Currency symbol: if you display amounts using different currencies then you may need to add it.
- Negative values: for money it's not uncommon to display negative values with a formatting that it's not the same one used for plain numbers.