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.
The DecimalFormat class has a pretty straightforward functionality and is easy to use. However, depending on your system's region you might run into some problems. Internationalization will cause your application to behave in a way you may not expect in some cases.
For example, you might be using this class to parse a number from a String
.
In this case, you may find that when the application executes in a computer in a French region you will be getting a ParseException
, because the computer is expecting different symbols.
Here is where the DecimalFormatSymbols class becomes very useful.
In the following code snippet, I'll show you how to configure the DecimalFormat class to parse numbers using the Spanish formatting symbols regardless of the system's region.
// We create our formatter using a DecimalFormat Instance.
// We use this method instead of (new DecimalFormat(String pattern))
// because in computers with different locales, we may have problems when
// setting the pattern. This way we assure we always work with the same variables.
DecimalFormat format = (DecimalFormat)DecimalFormat.getInstance(Locale.ENGLISH);
// We set the typical pattern with thousand separator and two decimal places
format.applyPattern("#,##0.00");
// Now we do the work to change the formatting symbols
// We will set the typical spanish symbols
DecimalFormatSymbols dfs = format.getDecimalFormatSymbols();
dfs.setDecimalSeparator(',');
dfs.setGroupingSeparator('.');
format.setDecimalFormatSymbols(dfs);
// We do two simple tests
System.out.println(format.format(1000234234.56772345d));
try {
System.out.println(format.parse("1.258.254,25"));
} catch (ParseException ex) {
ex.printStackTrace();
}