Parse number with format : Number Format « Data Type « Java






Parse number with format

        

/*
 * Copyright 2002-2006 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.
 */

//package jacky.lanlan.song.extension.struts.util;

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

/**
 * Miscellaneous utility methods for number conversion and parsing.
 * Mainly for internal use within the framework; consider Jakarta's
 * Commons Lang for a more comprehensive suite of string utilities.
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @since 1.1.2
 */
public abstract class NumberUtils {
  /**
   * Parse the given text into a number instance of the given target class,
   * using the corresponding default <code>decode</code> methods. Trims the
   * input <code>String</code> before attempting to parse the number. Supports
   * numbers in hex format (with leading 0x) and in octal format (with leading 0).
   * @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 java.lang.Byte#decode
   * @see java.lang.Short#decode
   * @see java.lang.Integer#decode
   * @see java.lang.Long#decode
   * @see #decodeBigInteger(String)
   * @see java.lang.Float#valueOf
   * @see java.lang.Double#valueOf
   * @see java.math.BigDecimal#BigDecimal(String)
   */
  public static Number parseNumber(String text, Class<?> targetClass) {
  //  Assert.notNull(text, "Text must not be null");
    //Assert.notNull(targetClass, "Target class must not be null");

    String trimmed = text.trim();

    if (targetClass.equals(Byte.class)) {
      return Byte.decode(trimmed);
    }
    else if (targetClass.equals(Short.class)) {
      return Short.decode(trimmed);
    }
    else if (targetClass.equals(Integer.class)) {
      return Integer.decode(trimmed);
    }
    else if (targetClass.equals(Long.class)) {
      return Long.decode(trimmed);
    }
    else if (targetClass.equals(BigInteger.class)) {
      return decodeBigInteger(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 java.text.NumberFormat#parse
   * @see #convertNumberToTargetClass
   * @see #parseNumber(String, Class)
   */
  public static Number parseNumber(String text, Class<?> targetClass, NumberFormat numberFormat) {
    if (numberFormat != null) {
      //Assert.notNull(text, "Text must not be null");
    //  Assert.notNull(targetClass, "Target class must not be null");
      try {
        Number number = numberFormat.parse(text.trim());
        return convertNumberToTargetClass(number, targetClass);
      }
      catch (ParseException ex) {
        throw new IllegalArgumentException(ex.getMessage());
      }
    }
    return parseNumber(text, targetClass);
  }

  /**
   * Decode a {@link java.math.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 java.lang.Byte
   * @see java.lang.Short
   * @see java.lang.Integer
   * @see java.lang.Long
   * @see java.math.BigInteger
   * @see java.lang.Float
   * @see java.lang.Double
   * @see java.math.BigDecimal
   */
  public static Number convertNumberToTargetClass(Number number, Class<?> targetClass)
      throws IllegalArgumentException {

  //  Assert.notNull(number, "Number must not be null");
  //  Assert.notNull(targetClass, "Target class must not be null");

    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(Float.class)) {
      return new Float(number.floatValue());
    }
    else if (targetClass.equals(Double.class)) {
      return new Double(number.doubleValue());
    }
    else if (targetClass.equals(BigInteger.class)) {
      return BigInteger.valueOf(number.longValue());
    }
    else if (targetClass.equals(BigDecimal.class)) {
      // using 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
   */
  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 examples in the same category

1.The Uppercase Option
2.Using the Format Flags
3.The Format Specifiers
4.NumberFormat with Constant Locale UsageNumberFormat with Constant Locale Usage
5.Number Format by locale
6.demonstrates the %n and %% format specifiers:
7.demonstrates the minimum field-width specifier by applying it to the %f conversion:
8.Create a table of squares and cubes.
9.precision modifier: Format 4 decimal places
10.precision modifier: Format to 2 decimal places in a 16 character field
11.precision modifier: Display at most 15 characters in a string
12.left justification: Right justify by default
13.left justification: left justify
14.Demonstrate the space format specifiers.
15.Using an Argument Index
16.the NumberFormat object is created once when the program starts.
17.Default rounding mode
18.RoundingMode.HALF_DOWN
19.RoundingMode.FLOOR
20.RoundingMode.CEILING
21.Format a number our way and the default way
22.Format a number to currencyFormat a number to currency
23.Number Format with LocaleNumber Format with Locale
24.Add leading zeroes to a number
25.Decimal Format DemoDecimal Format Demo
26.Parse number with NumberFormat and Locale
27.Formatting and Parsing a Locale-Specific Percentage
28.Format a number with DecimalFormat
29.Parse a number with NumberFormat and Locale.CANADA
30.Format a number with leading zeroes
31.Format a number for a locale
32.Formatting and Parsing a Number for a Locale
33.Display numbers in scientific notation
34.Format for GERMAN locale
35.Format for the default locale
36.Displaying numbers with commas
37.Formatting a Number in Exponential Notation
38.Using only 0's to the left of E forces no decimal point
39.Parse a GERMAN number
40.Formatting and Parsing Locale-Specific Currency
41.Parse a number for a locale
42.Use grouping to display a number
43.Number format viewer
44.A number formatter for logarithmic values. This formatter does not support parsing.
45.A custom number formatter that formats numbers as hexadecimal strings.
46.NumberFormat and locale
47.PrintfFormat allows the formatting of an array of objects embedded within a string.