Numbers to Strings with custom symbols // DecimalFormat - DecimalFormatSymbols
When printing reports or casting Strings to Numbers, it's very useful to take advantage of the DecimalFormat class found in the java.text
package.
This class is pretty straightforward and easy to use, but some problems may be found when your work with this class in computers from other countries. Internationalization will cause your program to behave in a way you may not expect in some cases.
If you use this class to parse a number to a String, you may find that when a user enters a number in a french computer you will be getting a ParseException, because the computer is expecting different symbols. Here is where the DecimalFormatSymbols class becomes very useful.
With the following code, I'll show you how easy is to change the symbols and make them independent of different Locales.
1// We create our formatter using a DecimalFormat Instance.
2// We use this method instead of (new DecimalFormat(String pattern))
3// because in computers with different locales, we may have problems when
4// setting the pattern. This way we assure we always work with the same variables.
5DecimalFormat format = (DecimalFormat)DecimalFormat.getInstance(Locale.ENGLISH);
6// We set the typical pattern with thousand separator and two decimal places
7format.applyPattern("#,##0.00");
8// Now we do the work to change the formatting symbols
9// We will set the typical spanish symbols
10DecimalFormatSymbols dfs = format.getDecimalFormatSymbols();
11dfs.setDecimalSeparator(',');
12dfs.setGroupingSeparator('.');
13format.setDecimalFormatSymbols(dfs);
14// We do two simple tests
15System.out.println(format.format(1000234234.56772345d));
16try {
17 System.out.println(format.parse("1.258.254,25"));
18} catch (ParseException ex) {
19 ex.printStackTrace();
20}