Is there a way to format currency conditionally depending on number of decimals?
For example :
CHF 1’200.00 becomes CHF 1’200.-
CHF 1’200.2 becomes CHF 1’200.20
CHF 1’200.20 becomes CHF 1’200.20
MIN_FRACTION_DIGITS attribute will set it all to .00, which solves 2nd and 3rd case, but will not solve the first one.
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
Is there a way to do that? Or at least format decimals as subscript, for example?
2
Answers
The only way I see is to set the settings for the
NumberFormatter
based on a condition and then adding.-
if the result is a whole number.This should cover the cases in your question:
1200.00
->CHF 1'200.-
1200
->CHF 1'200.-
1200.20
->CHF 1'200.20
1200.2
->CHF 1'200.20
You can use a regular expression replace with a strictly-formatted value where decimals are always included to replace the zero padded values with a custom ending and will work with various locales that have different monetary separators.
This function will work even if you switch to other locales with different separators and currencies. Note that this could become confusing for some since it appears like a negative value.
Also note that if you use PHP earlier than 8.0 you may need to replace the type hint on the function’s last
$value
parameter tomixed
since earlier versions don’t support union types.