Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format currency to local locale, but ignore .00 decimal places

I am trying to display a price for an item, in the relative currency given with the data, in the users locale format.

e.g. The item is in EUR and in UK should be displayed as €123.64 but in France should be displayed as 123,64 €

I want the currency symbol and decimal separator to be placed based on the users locale.

However, the piece that is getting me stuck is how to strip the .00 if the item has no pence/cents value.

I have tried using

NumberFormat f = NumberFormat.getInstance(loc);
if (f instanceof DecimalFormat) {
    ((DecimalFormat)f).setDecimalSeparatorAlwaysShown(false);
}

from DecimalFormat.html#setCurrency

but it doesn't have a currency symbol, even when I try f.setCurrency().

I have also tried changing getInstance to getCurrencyInstance, which now applies the currency symbol, but ignores the setDecimalSeparatorAlwaysShown(false) part.

I've thought about checking to see if the remainder is 0, and then stripping it out, but that would require me checking/knowing what the decimal separator is, which although possibly doable, is pretty hacky.

Does anyone know a way of doing all these things?!

like image 675
Russ Wheeler Avatar asked May 01 '15 11:05

Russ Wheeler


1 Answers

Ok, I've been completely stupid and blind, and didn't notice the method

setMaximumFractionDigits(int)

I've now set this to 0 if there is the decimal part is 0.

like image 75
Russ Wheeler Avatar answered Sep 28 '22 02:09

Russ Wheeler