View Javadoc
1   package org.csveed.bean.conversion;
2   
3   import static org.csveed.bean.conversion.ConversionUtil.trimAllWhitespace;
4   
5   import java.math.BigDecimal;
6   import java.math.BigInteger;
7   import java.text.DecimalFormat;
8   import java.text.NumberFormat;
9   import java.text.ParseException;
10  
11  public abstract class NumberUtils {
12  
13      @SuppressWarnings("unchecked")
14      public static <T extends Number> T convertNumberToTargetClass(Number number, Class<T> targetClass)
15              throws IllegalArgumentException {
16  
17          if (targetClass.isInstance(number)) {
18              return (T) number;
19          } else if (targetClass.equals(Byte.class)) {
20              long value = number.longValue();
21              if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
22                  raiseOverflowException(number, targetClass);
23              }
24              return (T) Byte.valueOf(number.byteValue());
25          } else if (targetClass.equals(Short.class)) {
26              long value = number.longValue();
27              if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
28                  raiseOverflowException(number, targetClass);
29              }
30              return (T) Short.valueOf(number.shortValue());
31          } else if (targetClass.equals(Integer.class)) {
32              long value = number.longValue();
33              if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
34                  raiseOverflowException(number, targetClass);
35              }
36              return (T) Integer.valueOf(number.intValue());
37          } else if (targetClass.equals(Long.class)) {
38              return (T) Long.valueOf(number.longValue());
39          } else if (targetClass.equals(BigInteger.class)) {
40              if (number instanceof BigDecimal) {
41                  // do not lose precision - use BigDecimal's own conversion
42                  return (T) ((BigDecimal) number).toBigInteger();
43              }
44              // original value is not a Big* number - use standard long conversion
45              return (T) BigInteger.valueOf(number.longValue());
46          } else if (targetClass.equals(Float.class)) {
47              return (T) Float.valueOf(number.floatValue());
48          } else if (targetClass.equals(Double.class)) {
49              return (T) Double.valueOf(number.doubleValue());
50          } else if (targetClass.equals(BigDecimal.class)) {
51              // always use BigDecimal(String) here to avoid unpredictability of BigDecimal(double)
52              // (see BigDecimal javadoc for details)
53              return (T) new BigDecimal(number.toString());
54          } else {
55              throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
56                      number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]");
57          }
58      }
59  
60      private static void raiseOverflowException(Number number, Class targetClass) {
61          throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
62                  number.getClass().getName() + "] to target class [" + targetClass.getName() + "]: overflow");
63      }
64  
65      @SuppressWarnings("unchecked")
66      public static <T extends Number> T parseNumber(String text, Class<T> targetClass) {
67          String trimmed = trimAllWhitespace(text);
68  
69          if (targetClass.equals(Byte.class)) {
70              return (T) (isHexNumber(trimmed) ? Byte.decode(trimmed) : Byte.valueOf(trimmed));
71          } else if (targetClass.equals(Short.class)) {
72              return (T) (isHexNumber(trimmed) ? Short.decode(trimmed) : Short.valueOf(trimmed));
73          } else if (targetClass.equals(Integer.class)) {
74              return (T) (isHexNumber(trimmed) ? Integer.decode(trimmed) : Integer.valueOf(trimmed));
75          } else if (targetClass.equals(Long.class)) {
76              return (T) (isHexNumber(trimmed) ? Long.decode(trimmed) : Long.valueOf(trimmed));
77          } else if (targetClass.equals(BigInteger.class)) {
78              return (T) (isHexNumber(trimmed) ? decodeBigInteger(trimmed) : new BigInteger(trimmed));
79          } else if (targetClass.equals(Float.class)) {
80              return (T) Float.valueOf(trimmed);
81          } else if (targetClass.equals(Double.class)) {
82              return (T) Double.valueOf(trimmed);
83          } else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) {
84              return (T) new BigDecimal(trimmed);
85          } else {
86              throw new IllegalArgumentException(
87                      "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]");
88          }
89      }
90  
91      public static <T extends Number> T parseNumber(String text, Class<T> targetClass, NumberFormat numberFormat) {
92          if (numberFormat != null) {
93              DecimalFormat decimalFormat = null;
94              boolean resetBigDecimal = false;
95              if (numberFormat instanceof DecimalFormat) {
96                  decimalFormat = (DecimalFormat) numberFormat;
97                  if (BigDecimal.class.equals(targetClass) && !decimalFormat.isParseBigDecimal()) {
98                      decimalFormat.setParseBigDecimal(true);
99                      resetBigDecimal = true;
100                 }
101             }
102             try {
103                 Number number = numberFormat.parse(trimAllWhitespace(text));
104                 return convertNumberToTargetClass(number, targetClass);
105             } catch (ParseException ex) {
106                 throw new IllegalArgumentException("Could not parse number: " + ex.getMessage());
107             } finally {
108                 if (resetBigDecimal && decimalFormat != null) {
109                     decimalFormat.setParseBigDecimal(false);
110                 }
111             }
112         }
113         return parseNumber(text, targetClass);
114     }
115 
116     private static boolean isHexNumber(String value) {
117         int index = value.startsWith("-") ? 1 : 0;
118         return value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index);
119     }
120 
121     private static BigInteger decodeBigInteger(String value) {
122         int radix = 10;
123         int index = 0;
124         boolean negative = false;
125 
126         // Handle minus sign, if present.
127         if (value.startsWith("-")) {
128             negative = true;
129             index++;
130         }
131 
132         // Handle radix specifier, if present.
133         if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
134             index += 2;
135             radix = 16;
136         } else if (value.startsWith("#", index)) {
137             index++;
138             radix = 16;
139         } else if (value.startsWith("0", index) && value.length() > 1 + index) {
140             index++;
141             radix = 8;
142         }
143 
144         BigInteger result = new BigInteger(value.substring(index), radix);
145         return negative ? result.negate() : result;
146     }
147 
148 }