Example usage for java.text NumberFormat parse

List of usage examples for java.text NumberFormat parse

Introduction

In this page you can find the example usage for java.text NumberFormat parse.

Prototype

public Number parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a number.

Usage

From source file:Main.java

/**
 * Adopted from http://jgnash.svn.sourceforge.net/viewvc/jgnash/jgnash2/trunk/src/jgnash/imports/qif/QifUtils.java
 *//*from   www . j  a  v a2  s.  c om*/
public static long parseMoney(String money) {
    String sMoney = money;

    if (sMoney != null) {
        BigDecimal bdMoney;
        sMoney = sMoney.trim(); // to be safe
        try {
            bdMoney = new BigDecimal(sMoney);
            return moneyAsLong(bdMoney);
        } catch (NumberFormatException e) {
            /* there must be commas, etc in the number.  Need to look for them
             * and remove them first, and then try BigDecimal again.  If that
             * fails, then give up and use NumberFormat and scale it down
             * */
            String[] split = MONEY_PREFIX_PATTERN.split(sMoney);
            if (split.length > 2) {
                StringBuilder buf = new StringBuilder();
                if (sMoney.startsWith("-")) {
                    buf.append('-');
                }
                for (int i = 0; i < split.length - 1; i++) {
                    buf.append(split[i]);
                }
                buf.append('.');
                buf.append(split[split.length - 1]);
                try {
                    bdMoney = new BigDecimal(buf.toString());
                    return moneyAsLong(bdMoney);
                } catch (final NumberFormatException e2) {
                    Log.e("QifUtils", "Second parse attempt failed, falling back to rounding");
                }
            }
            NumberFormat formatter = NumberFormat.getNumberInstance();
            try {
                Number num = formatter.parse(sMoney);
                BigDecimal bd = new BigDecimal(num.floatValue());
                if (bd.scale() > 6) {
                    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                }
                return moneyAsLong(bd);
            } catch (ParseException ignored) {
            }
            Log.e("QifUtils", "Could not parse money " + sMoney);
        }
    }
    return 0;
}

From source file:driimerfinance.helpers.FinanceHelper.java

/**
 * unformats a formatted number to be a double again
 * /*from   w  w  w  . j  a v  a  2 s. c  o m*/
 * @param string number to convert
 * @return an unformatted number to be used for db interactions
 */
public static double unformatAmount(String formattedNumber) {
    NumberFormat numberFormatter = NumberFormat.getCurrencyInstance();
    Number number = null;
    try {
        number = numberFormatter.parse(formattedNumber);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    double unformattedNumber = number.doubleValue();
    return unformattedNumber;
}

From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java

@SuppressWarnings("squid:S3776")
private static Object convertPrimitiveValue(String value, Class<?> type) throws ParseException {
    if (type.equals(Boolean.class) || type.equals(Boolean.TYPE)) {
        return value.toLowerCase().trim().equals("true");
    } else {/*from   ww w. j  a v a  2  s. c o m*/
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        Number num = numberFormat.parse(value);
        if (type.equals(Byte.class) || type.equals(Byte.TYPE)) {
            return num.byteValue();
        } else if (type.equals(Double.class) || type.equals(Double.TYPE)) {
            return num.doubleValue();
        } else if (type.equals(Float.class) || type.equals(Float.TYPE)) {
            return num.floatValue();
        } else if (type.equals(Integer.class) || type.equals(Integer.TYPE)) {
            return num.intValue();
        } else if (type.equals(Long.class) || type.equals(Long.TYPE)) {
            return num.longValue();
        } else if (type.equals(Short.class) || type.equals(Short.TYPE)) {
            return num.shortValue();
        } else {
            return null;
        }
    }
}

From source file:NumberUtils.java

/**
 * 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/*w w  w. j a  va  2s .c  o  m*/
 * @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) {
        try {
            Number number = numberFormat.parse(text.trim());
            return convertNumberToTargetClass(number, targetClass);
        } catch (ParseException ex) {
            throw new IllegalArgumentException(ex.getMessage());
        }
    } else {
        return parseNumber(text, targetClass);
    }
}

From source file:NumberUtils.java

/**
 * 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/*  w  ww.  j  a  v a2s.c  om*/
 * @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) {

        try {
            Number number = numberFormat.parse(text.trim());
            return convertNumberToTargetClass(number, targetClass);
        } catch (ParseException ex) {
            throw new IllegalArgumentException(ex.getMessage());
        }
    } else {
        return parseNumber(text, targetClass);
    }
}

From source file:org.openestate.io.core.NumberUtils.java

/**
 * Convert a string value into a number.
 *
 * @param value/*  w  ww  . j a  v  a2s .  c o m*/
 * the string value to convert
 *
 * @param integerOnly
 * wether only the integer part of the value is parsed
 *
 * @param locales
 * locales, against which the value is parsed
 *
 * @return
 * numeric value for the string
 *
 * @throws NumberFormatException
 * if the string is not a valid number
 */
public static Number parseNumber(String value, boolean integerOnly, Locale... locales)
        throws NumberFormatException {
    value = StringUtils.trimToNull(value);
    if (value == null)
        return null;

    // ignore leading plus sign
    if (value.startsWith("+"))
        value = StringUtils.trimToNull(value.substring(1));

    // remove any spaces
    value = StringUtils.replace(value, StringUtils.SPACE, StringUtils.EMPTY);

    if (ArrayUtils.isEmpty(locales))
        locales = new Locale[] { Locale.getDefault() };

    for (Locale locale : locales) {
        // check, if the value is completely numeric for the locale
        if (!isNumeric(value, locale))
            continue;
        try {
            NumberFormat format = NumberFormat.getNumberInstance(locale);
            format.setMinimumFractionDigits(0);
            format.setGroupingUsed(false);
            format.setParseIntegerOnly(integerOnly);
            return format.parse(value);
        } catch (ParseException ex) {
        }
    }
    throw new NumberFormatException("The provided value '" + value + "' is not numeric!");
}

From source file:NumberUtils.java

/**
 * 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/*www  .  j a v a2s. co m*/
 * @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);
}

From source file:com.enadein.carlogbook.db.CommonUtils.java

public static double parsePriceString(String string) {
    NumberFormat format = getPriceNumberFormat();

    Number result = 0;//from   w w w.j  a va2 s.  co m
    try {
        result = format.parse(string.replace(',', '.'));
    } catch (ParseException e) {
        //nothing
    }

    return result.doubleValue();
}

From source file:com.silverpeas.util.StringUtil.java

/**
   * Parse a String into a float using the specified locale.
   */*from w ww  .j av a  2  s .c o  m*/
   * @param value the string to be parsed into a float
   * @param language the language for defining the locale
   * @return the float value.
   * @throws ParseException
   */
  public static float floatValue(String value, String language) throws ParseException {
      String lang = language;
      if (!StringUtil.isDefined(language)) {
          lang = I18NHelper.defaultLanguage;
      }
      NumberFormat numberFormat = NumberFormat.getInstance(new Locale(lang));
      return numberFormat.parse(value).floatValue();
  }

From source file:org.protorabbit.model.impl.DefaultEngine.java

static IParameter getParameter(String text, Character lastToken) {
    Object value = null;// www. j  av a2s. com
    text = text.trim();
    int type = -1;
    if (lastToken != null && lastToken.charValue() == '\"') {
        type = IParameter.STRING;
        // set the value to not include the quotes
        value = text.substring(1, text.length() - 1);
    } else if ("true".equals(text) || "false".equals(text)) {
        type = IParameter.BOOLEAN;
        value = new Boolean(("true".equals(text)));
    } else if ("null".equals(text)) {
        type = IParameter.NULL;
    } else if (text.startsWith("{") && text.endsWith("}")) {
        try {
            value = new JSONObject(text);
            type = IParameter.OBJECT;
        } catch (JSONException e) {
            throw new RuntimeException("Error parsing JSON parameter " + text);
        }
    } else if (text.startsWith("[") && text.endsWith("]")) {
        try {
            value = new JSONArray(text);
            type = IParameter.ARRAY;
        } catch (JSONException e) {
            throw new RuntimeException("Error parsing JSON parameter " + text);
        }
    } else {
        try {
            NumberFormat nf = NumberFormat.getInstance();
            value = nf.parse(text);
            type = IParameter.NUMBER;
        } catch (ParseException pe) {
            // do nothing
        }
    }
    if (type != -1) {
        return new Parameter(type, value);
    } else {
        throw new RuntimeException("Error parsing parameter " + text);
    }
}