Last week, while I was happily vacationing in Spain, I received an email from an NMoneys user with a deceptively simple question:
“When formatting a Money instance, how does one remove the decimals if the amount is integral?”
It is not straightforward
Even though Money
supports custom formatting via .ToString(format)
and .Format()
overrides, none of them allows conditional treatment depending on the nature of the amount.
I faced myself a similar requirement, but in my case I was not to use the currency symbol, but fix the ISO code at the beginning, followed by the amount with two decimals or none if integral. My case was easily solved with the following extension method…
…that makes use of the Digit placeholder that will prevent digits to be displayed when not present.
Was That the question?
No. But, trying to make a point here…
In my case the format was artificially constrained and it cannot be applied to all currencies:
- not all symbols appear in the same position. Some are prefixes and some are postfixes, with or without space. And let’s not get started with negative patterns.
- not all currencies have two significant decimals
And the answer is
I tried to solve the issue at its lowest level, trying to find a format pattern that did the job or looking at how the symbol and patterns are used behind the scenes. In both cases I ended in a cul-de-sac: could not get in the middle of the number formatting since it is an externally-defined method.
But then I got a hint from the ever useful Stackoverflow: we want different behavior depending whether the number has decimals or not. And here’s the adapted solution using NMoneys:
Hope this helps someone else that has the same requirement and did not figure out already.