Java Parse Number parseNumber(String text, Class targetClass, NumberFormat numberFormat)

Here you can find the source of parseNumber(String text, Class targetClass, NumberFormat numberFormat)

Description

Parse the given text into a number instance of the given target class, using the given NumberFormat.

License

Apache License

Parameter

Parameter Description
text the text to convert
targetClass the target class to parse into
numberFormat the NumberFormat to use for parsing (if <code>null</code>, this method falls back to <code>parseNumber(String, Class)</code>)

Exception

Parameter Description
IllegalArgumentException if the target class is not supported(i.e. not a standard Number subclass as included in the JDK)

Return

the parsed number

Declaration

@SuppressWarnings("rawtypes")
public static Number parseNumber(String text, Class targetClass,
        NumberFormat numberFormat) 

Method Source Code

//package com.java2s;
/*/*from   w  w w. j a  va 2s. c om*/
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;

public class Main {
    /**
     * Parse the given text into a number instance of the given target class,
     * using the corresponding <code>decode</code> / <code>valueOf</code> methods.
     * <p>Trims the input <code>String</code> before attempting to parse the number.
     * Supports numbers in hex format (with leading "0x", "0X" or "#") as well.
     * @param text the text to convert
     * @param targetClass the target class to parse into
     * @return the parsed number
     * @throws IllegalArgumentException if the target class is not supported
     * (i.e. not a standard Number subclass as included in the JDK)
     * @see Byte#decode
     * @see Short#decode
     * @see Integer#decode
     * @see Long#decode
     * @see #decodeBigInteger(String)
     * @see Float#valueOf
     * @see Double#valueOf
     * @see BigDecimal#BigDecimal(String)
     */
    @SuppressWarnings("rawtypes")
    public static Number parseNumber(String text, Class targetClass) {

        String trimmed = text.trim();

        if (targetClass.equals(Byte.class)) {
            return (isHexNumber(trimmed) ? Byte.decode(trimmed) : Byte
                    .valueOf(trimmed));
        } else if (targetClass.equals(Short.class)) {
            return (isHexNumber(trimmed) ? Short.decode(trimmed) : Short
                    .valueOf(trimmed));
        } else if (targetClass.equals(Integer.class)) {
            return (isHexNumber(trimmed) ? Integer.decode(trimmed)
                    : Integer.valueOf(trimmed));
        } else if (targetClass.equals(Long.class)) {
            return (isHexNumber(trimmed) ? Long.decode(trimmed) : Long
                    .valueOf(trimmed));
        } else if (targetClass.equals(BigInteger.class)) {
            return (isHexNumber(trimmed) ? decodeBigInteger(trimmed)
                    : new BigInteger(trimmed));
        } else if (targetClass.equals(Float.class)) {
            return Float.valueOf(trimmed);
        } else if (targetClass.equals(Double.class)) {
            return Double.valueOf(trimmed);
        } else if (targetClass.equals(BigDecimal.class)
                || targetClass.equals(Number.class)) {
            return new BigDecimal(trimmed);
        } else {
            throw new IllegalArgumentException("Cannot convert String ["
                    + text + "] to target class [" + targetClass.getName()
                    + "]");
        }
    }

    /**
     * Parse the given text into a number instance of the given target class,
     * using the given NumberFormat. Trims the input <code>String</code>
     * before attempting to parse the number.
     * @param text the text to convert
     * @param targetClass the target class to parse into
     * @param numberFormat the NumberFormat to use for parsing (if <code>null</code>,
     * this method falls back to <code>parseNumber(String, Class)</code>)
     * @return the parsed number
     * @throws IllegalArgumentException if the target class is not supported
     * (i.e. not a standard Number subclass as included in the JDK)
     * @see NumberFormat#parse
     * @see #convertNumberToTargetClass
     * @see #parseNumber(String, Class)
     */
    @SuppressWarnings("rawtypes")
    public static Number parseNumber(String text, Class targetClass,
            NumberFormat numberFormat) {
        if (numberFormat != null) {

            DecimalFormat decimalFormat = null;
            boolean resetBigDecimal = false;
            if (numberFormat instanceof DecimalFormat) {
                decimalFormat = (DecimalFormat) numberFormat;
                if (BigDecimal.class.equals(targetClass)
                        && !decimalFormat.isParseBigDecimal()) {
                    decimalFormat.setParseBigDecimal(true);
                    resetBigDecimal = true;
                }
            }
            try {
                Number number = numberFormat.parse(text.trim());
                return convertNumberToTargetClass(number, targetClass);
            } catch (ParseException ex) {
                IllegalArgumentException iae = new IllegalArgumentException(
                        "Could not parse number: " + ex.getMessage());
                iae.initCause(ex);
                throw iae;
            } finally {
                if (resetBigDecimal) {
                    decimalFormat.setParseBigDecimal(false);
                }
            }
        } else {
            return parseNumber(text, targetClass);
        }
    }

    /**
     * Determine whether the given value String indicates a hex number, i.e. needs to be
     * passed into <code>Integer.decode</code> instead of <code>Integer.valueOf</code> (etc).
     */
    private static boolean isHexNumber(String value) {
        int index = (value.startsWith("-") ? 1 : 0);
        return (value.startsWith("0x", index)
                || value.startsWith("0X", index) || value.startsWith("#",
                index));
    }

    /**
     * Decode a {@link BigInteger} from a {@link String} value.
     * Supports decimal, hex and octal notation.
     * @see BigInteger#BigInteger(String, int)
     */
    private static BigInteger decodeBigInteger(String value) {
        int radix = 10;
        int index = 0;
        boolean negative = false;

        // Handle minus sign, if present.
        if (value.startsWith("-")) {
            negative = true;
            index++;
        }

        // Handle radix specifier, if present.
        if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        } else if (value.startsWith("#", index)) {
            index++;
            radix = 16;
        } else if (value.startsWith("0", index)
                && value.length() > 1 + index) {
            index++;
            radix = 8;
        }

        BigInteger result = new BigInteger(value.substring(index), radix);
        return (negative ? result.negate() : result);
    }

    /**
     * Convert the given number into an instance of the given target class.
     * @param number the number to convert
     * @param targetClass the target class to convert to
     * @return the converted number
     * @throws IllegalArgumentException if the target class is not supported
     * (i.e. not a standard Number subclass as included in the JDK)
     * @see Byte
     * @see Short
     * @see Integer
     * @see Long
     * @see BigInteger
     * @see Float
     * @see Double
     * @see BigDecimal
     */
    @SuppressWarnings("rawtypes")
    public static Number convertNumberToTargetClass(Number number,
            Class targetClass) throws IllegalArgumentException {

        if (targetClass.isInstance(number)) {
            return number;
        } else if (targetClass.equals(Byte.class)) {
            long value = number.longValue();
            if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return new Byte(number.byteValue());
        } else if (targetClass.equals(Short.class)) {
            long value = number.longValue();
            if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return new Short(number.shortValue());
        } else if (targetClass.equals(Integer.class)) {
            long value = number.longValue();
            if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return new Integer(number.intValue());
        } else if (targetClass.equals(Long.class)) {
            return new Long(number.longValue());
        } else if (targetClass.equals(BigInteger.class)) {
            if (number instanceof BigDecimal) {
                // do not lose precision - use BigDecimal's own conversion
                return ((BigDecimal) number).toBigInteger();
            } else {
                // original value is not a Big* number - use standard long conversion
                return BigInteger.valueOf(number.longValue());
            }
        } else if (targetClass.equals(Float.class)) {
            return new Float(number.floatValue());
        } else if (targetClass.equals(Double.class)) {
            return new Double(number.doubleValue());
        } else if (targetClass.equals(BigDecimal.class)) {
            // always use BigDecimal(String) here to avoid unpredictability of BigDecimal(double)
            // (see BigDecimal javadoc for details)
            return new BigDecimal(number.toString());
        } else {
            throw new IllegalArgumentException("Could not convert number ["
                    + number + "] of type [" + number.getClass().getName()
                    + "] to unknown target class [" + targetClass.getName()
                    + "]");
        }
    }

    /**
     * Raise an overflow exception for the given number and target class.
     * @param number the number we tried to convert
     * @param targetClass the target class we tried to convert to
     */
    @SuppressWarnings("rawtypes")
    private static void raiseOverflowException(Number number,
            Class targetClass) {
        throw new IllegalArgumentException("Could not convert number ["
                + number + "] of type [" + number.getClass().getName()
                + "] to target class [" + targetClass.getName()
                + "]: overflow");
    }
}

Related

  1. parseNumber(final String source, final String conversionPattern)
  2. parseNumber(String number)
  3. parseNumber(String number)
  4. parseNumber(String s)
  5. parseNumber(String text, Class targetClass)
  6. parseNumber(String text, Class targetClass)
  7. parseNumeric(String value)