Greg
Greg

Reputation: 709

How to format a number for european language

I have a Double: 5096,54 I need to format it as : 5.096,54 (european format for currency) I'm trying with this code without any success.

 Locale l = Locale.getDefault(); // ("fr" in my case)
 // Get the formatter for the specific locale
 NumberFormat formatter = NumberFormat.getNumberInstance(l);

 // Always 2 decimals
 formatter.setMinimumFractionDigits(2);
 formatter.setMaximumFractionDigits(2);

 // Format
 return formatter.format(d);

Output: 5 096,54 when I'm expecting 5.096,54 Any idea why it fails?

Upvotes: 4

Views: 4892

Answers (2)

earthw0rmjim
earthw0rmjim

Reputation: 19417

You could do the following:

Locale l = Locale.getDefault();
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(l);

DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator('.'); // setting the thousand separator
// symbols.setDecimalSeparator(','); optionally setting the decimal separator

formatter.setDecimalFormatSymbols(symbols);
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);

String formattedString = formatter.format(yourDouble);

Upvotes: 2

SCouto
SCouto

Reputation: 7928

It's working for me with Spanish locale:

    Double d = 5096.54;

    Locale l = Locale.getDefault(); 

    NumberFormat formatter = NumberFormat.getNumberInstance(l);

    formatter.setMinimumFractionDigits(2);
    formatter.setMaximumFractionDigits(2);

    String d1 = formatter.format(d);

Result: 5.096,54

It seems the French locale use something that looks like a space as a thousands-separator, you can check this question:

Java FRANCE/FRENCH Locale thousands separator looks like space but not actually

They fix it with this workaround:

DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRANCE);
DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
char thousandSep = symbols.getGroupingSeparator();

input =input.replace(thousandSep, '.'); 

You can either use the same workaround or use the Spanish Locale (or any other that matches with your needs)

Upvotes: 2

Related Questions