View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
17   */
18  
19  package org.mycore.frontend.xeditor.validation;
20  
21  import java.text.DecimalFormat;
22  import java.text.DecimalFormatSymbols;
23  import java.text.NumberFormat;
24  import java.text.ParseException;
25  import java.util.Locale;
26  
27  /**
28   * Helper for decimal validators to convert string input into a decimal value for a given locale.
29   * 
30   * @author Frank L\u00FCtzenkirchen 
31   */
32  public class MCRDecimalConverter {
33  
34      private Locale locale = Locale.getDefault();
35  
36      public MCRDecimalConverter(String localeID) {
37          this.locale = new Locale(localeID);
38      }
39  
40      /**
41       * Converts a given text string to a decimal number, using the given locale.
42       * 
43       * @param value the text strin
44       * @return null, if the text contains illegal chars or can not be parsed
45       */
46      public Double string2double(String value) {
47          if (hasIllegalCharacters(value)) {
48              return null;
49          }
50  
51          NumberFormat nf = NumberFormat.getNumberInstance(locale);
52          if ((nf instanceof DecimalFormat) && hasMultipleDecimalSeparators(value, (DecimalFormat) nf)) {
53              return null;
54          }
55  
56          try {
57              return nf.parse(value).doubleValue();
58          } catch (ParseException e) {
59              return null;
60          }
61      }
62  
63      private boolean hasMultipleDecimalSeparators(String string, DecimalFormat df) {
64          DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
65          String patternNonDecimalSeparators = "[^" + dfs.getDecimalSeparator() + "]";
66          String decimalSeparatorsLeftOver = string.replaceAll(patternNonDecimalSeparators, "");
67          return (decimalSeparatorsLeftOver.length() > 1);
68      }
69  
70      private boolean hasIllegalCharacters(String string) {
71          return !string.matches("[0-9,.]+");
72      }
73  }