lunes, 7 mayo 2007

Numbers to Strings with custom symbols // DecimalFormat - DecimalFormatSymbols

When printing reports or casting Strings to Numbers, its very useful to use the DecimalFormat class found in java.text. 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 these 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.


/* We create our formatter using a DecimalFormat Instance.
         * We use these 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();
        }

Technorati Tags:

Posted by admin at 6:49 AM in Java

Google
 
« May »
SunMonTueWedThuFriSat
  12345
6789101112
13141516171819
20212223242526
2728293031