Coerces a Number to the specified numeric type. @param number the number to coerce @param type the target numeric type @return the coerced number @throws ELException if the number cannot be coerced to the target type
(final Number number, final Class<?> type)
| 315 | * @throws ELException if the number cannot be coerced to the target type |
| 316 | */ |
| 317 | protected static Number coerceToNumber(final Number number, final Class<?> type) throws ELException { |
| 318 | if (Long.TYPE == type || Long.class.equals(type)) { |
| 319 | return Long.valueOf(number.longValue()); |
| 320 | } |
| 321 | if (Double.TYPE == type || Double.class.equals(type)) { |
| 322 | return Double.valueOf(number.doubleValue()); |
| 323 | } |
| 324 | if (Integer.TYPE == type || Integer.class.equals(type)) { |
| 325 | return Integer.valueOf(number.intValue()); |
| 326 | } |
| 327 | if (BigInteger.class.equals(type)) { |
| 328 | if (number instanceof BigDecimal) { |
| 329 | return ((BigDecimal) number).toBigInteger(); |
| 330 | } |
| 331 | if (number instanceof BigInteger) { |
| 332 | return number; |
| 333 | } |
| 334 | return BigInteger.valueOf(number.longValue()); |
| 335 | } |
| 336 | if (BigDecimal.class.equals(type)) { |
| 337 | if (number instanceof BigDecimal) { |
| 338 | return number; |
| 339 | } |
| 340 | if (number instanceof BigInteger) { |
| 341 | return new BigDecimal((BigInteger) number); |
| 342 | } |
| 343 | return new BigDecimal(number.doubleValue()); |
| 344 | } |
| 345 | if (Byte.TYPE == type || Byte.class.equals(type)) { |
| 346 | return Byte.valueOf(number.byteValue()); |
| 347 | } |
| 348 | if (Short.TYPE == type || Short.class.equals(type)) { |
| 349 | return Short.valueOf(number.shortValue()); |
| 350 | } |
| 351 | if (Float.TYPE == type || Float.class.equals(type)) { |
| 352 | return Float.valueOf(number.floatValue()); |
| 353 | } |
| 354 | if (Number.class.equals(type)) { |
| 355 | return number; |
| 356 | } |
| 357 | |
| 358 | throw new ELException(MessageFactory.get("error.convert", number, number.getClass(), type)); |
| 359 | } |
| 360 | |
| 361 | /** |
| 362 | * Coerces an object to a Number of the specified type. |