1

I have a Struts 2 project where I display an item price. I want to change the format accorting to localization.

For example:

 locale en_GB : 75.9
 locale el_GR : 75,9

Currently I use the format in the messages for both locales :

{0,number,##0.00}

I tried changing the format in the one language to:

{0,number,##0,00}   

but then the displayed price was wrong as: 0,76 (moved everything to the decimal part).

Any suggestions?


EDIT:

Note that in my case i want to FORCE the comma as decimal separator for all locales in the application.

Panos
  • 7,227
  • 13
  • 60
  • 95
  • Can you show how do you use this format? – Aleksandr M Nov 21 '14 at 10:14
  • This is how I use it: – Panos Nov 21 '14 at 10:23
  • The decimal separator depends on locale. S2 will format numbers according to current locale so just leave `{0,number,##0.00}` that pattern and it should work. – Aleksandr M Nov 21 '14 at 10:42
  • Probably the error is just `gr_GR` instead of `el_GR`. BTW one could be interested in showing multiple localized strings (and numbers) in a locale-independent page (eg. a banner with the selection of the language, each name written in its language)... – Andrea Ligios Nov 21 '14 at 11:09
  • The question is not only for el_GR, it could be for any language. I want to force the comma as decimal separator for all locales – Panos Nov 21 '14 at 11:13
  • 1
    Why do you want to force that? Each locale has it own decimal separator and by changing it you are confusing users of your application. – Aleksandr M Nov 21 '14 at 11:18
  • Because the client requires to be able to view the application on two different languages, but to have everywhere the same way to represent prices. – Panos Nov 21 '14 at 12:10
  • Woah... the client is alway right, isn't it ? :/ Then you can use the code in the answer provided, with the default locale chosen, in a method of a BaseAction of your, extended by the other actions, and called only to format currencies. – Andrea Ligios Nov 21 '14 at 12:40
  • @Panos: Then don't format prices through S2 localization feature. – Aleksandr M Nov 21 '14 at 19:00

1 Answers1

1

You can use the DecimalFormat Constructor accepting both a pattern and a DecimalFormatSymbols, created by its constructor taking a Locale:

Locale greekLocale = new Locale("el", "GR");

// Thousands separator, decimal separator etc...
DecimalFormatSymbols greekDFS = DecimalFormatSymbols.getInstance(greekLocale);

// Your pattern, their symbols
NumberFormat nf = new DecimalFormat("#,##0.0##", greekDFS);

Take a look at the running demo. I've used el_GR by the way, with gr_GR it seems that the decimal separator is still the dot. Not sure what gr_GR is.

P.S: Here is an answer related to formatting patterns and TextProvider in Struts2, that might help future visitors

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243