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 abstract Number parse(String source, ParsePosition parsePosition);

Source Link

Document

Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, Long.MAX_VALUE] and with no decimals), otherwise a Double.

Usage

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to an int primitive.
 * //from   w  w w  .j a  v a 2 s. com
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)
 * @return the converted Integer value.
 */
public static Integer formatInt(String value, Locale locale) {
    Integer result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Integer.MIN_VALUE && num.doubleValue() <= Integer.MAX_VALUE) {
                result = new Integer(num.intValue());
            }
        }
    }

    return result;
}

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a long primitive.
 * //from   w  ww  . j a va2 s.  c o m
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)
 * @return the converted Long value.
 */
public static Long formatLong(String value, Locale locale) {
    Long result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Long.MIN_VALUE && num.doubleValue() <= Long.MAX_VALUE) {
                result = new Long(num.longValue());
            }
        }
    }

    return result;
}

From source file:com.almalence.util.Util.java

public static boolean isNumeric(String str) {
    NumberFormat formatter = NumberFormat.getInstance();
    ParsePosition pos = new ParsePosition(0);
    formatter.parse(str, pos);
    return str.length() == pos.getIndex();
}

From source file:com.haulmont.chile.core.datatypes.impl.NumberDatatype.java

protected Number parse(String value, NumberFormat format) throws ParseException {
    ParsePosition pos = new ParsePosition(0);
    Number res = format.parse(value.trim(), pos);
    if (pos.getIndex() != value.length()) {
        throw new ParseException(String.format("Unparseable number: \"%s\"", value), pos.getErrorIndex());
    }/* w  w w. j  a  v  a 2 s.c  om*/
    return res;
}

From source file:org.netxilia.api.impl.value.NumberParser.java

@Override
public IGenericValue parse(String text) {
    String input = preprocess(text);
    ParsePosition pp = new ParsePosition(0);

    for (NumberFormat format : this.formats) {
        pp.setIndex(0);/*  ww w  .  j a  v  a  2  s .  com*/
        Number number = format.parse(input, pp);
        if (number != null && input.length() == pp.getIndex()) {
            return new NumberValue(number.doubleValue());
        }
    }

    return null;
}

From source file:org.springframework.binding.convert.converters.FormattedStringToNumber.java

@SuppressWarnings("unchecked")
protected Object toObject(String string, Class<?> targetClass) throws Exception {
    ParsePosition parsePosition = new ParsePosition(0);
    NumberFormat format = numberFormatFactory.getNumberFormat();
    Number number = format.parse(string, parsePosition);
    if (number == null) {
        // no object could be parsed
        throw new InvalidFormatException(string, getPattern(format));
    }//from w w w .ja va  2  s . c  o  m
    if (!lenient) {
        if (string.length() != parsePosition.getIndex()) {
            // indicates a part of the string that was not parsed; e.g. ".5" in 1234.5 when parsing an Integer
            throw new InvalidFormatException(string, getPattern(format));
        }
    }
    return convertToNumberClass(number, (Class<? extends Number>) targetClass);
}

From source file:org.createnet.raptor.models.data.types.NumberRecord.java

@Override
public Number parseValue(Object value) {
    try {//  w  ww . j a v a2s .co m

        if (value instanceof Number) {
            return (Number) value;
        }

        if (value instanceof JsonNode) {

            JsonNode node = (JsonNode) value;

            if (node.isNumber()) {

                if (node.isInt() || node.isShort()) {
                    return (Number) node.asInt();
                }

                if (node.isDouble() || node.isFloat()) {
                    return (Number) node.asDouble();
                }

                if (node.isLong()) {
                    return (Number) node.asLong();
                }
            }

            if (node.isTextual()) {
                value = node.asText();
            }

        }

        NumberFormat formatter = NumberFormat.getInstance();
        ParsePosition pos = new ParsePosition(0);
        Number numVal = formatter.parse((String) value, pos);

        return numVal;
    } catch (Exception e) {
        throw new RaptorComponent.ParserException(e);
    }
}

From source file:de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest.ValueConverter.java

private Object convertStringToValue(Class<?> targetClass, String format, Locale locale, String value) {

    try {/* ww  w . j a  v  a2 s .c o m*/
        Locale effectiveLocale = locale != null ? locale : Locale.US;
        NumberFormat nf = new NumberFormatter(format).getNumberFormat(effectiveLocale);
        Number number = null;
        if (targetClass == BigDecimal.class) {
            ((DecimalFormat) nf).setParseBigDecimal(true);
            number = nf.parse(value, new ParsePosition(0));
        } else {
            number = nf.parse(value);
        }
        return convertNumberToNumber(targetClass, number);

    } catch (ParseException e) {
        // continue to exception
    }

    throw new IllegalArgumentException("Cannot convert to " + targetClass.getSimpleName() + ": " + value);
}

From source file:org.orcid.core.cli.MigrateFundingAmountToANumericValue.java

private BigDecimal getAmountAsBigDecimal(String amount, String currencyCode, Locale locale) throws Exception {
    try {/*from  w  w w . ja v  a2s .  c o m*/
        ParsePosition parsePosition = new ParsePosition(0);
        NumberFormat numberFormat = NumberFormat.getInstance(locale);
        Number number = null;
        if (!PojoUtil.isEmpty(currencyCode)) {
            Currency currency = Currency.getInstance(currencyCode);
            String currencySymbol = currency.getSymbol();
            number = numberFormat.parse(amount.replace(currencySymbol, StringUtils.EMPTY), parsePosition);
        } else {
            number = numberFormat.parse(amount, parsePosition);
        }
        if (parsePosition.getIndex() != amount.length())
            throw new Exception("Unable to parse amount into BigDecimal");
        return new BigDecimal(number.toString());
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.examples.with.different.packagename.testcarver.NumberConverter.java

/**
 * Convert a String into a <code>Number</code> object.
 * @param sourceType TODO//  w  ww. j  av a2s .c o m
 * @param targetType The type to convert the value to
 * @param value The String date value.
 * @param format The NumberFormat to parse the String value.
 *
 * @return The converted Number object.
 * @throws ConversionException if the String cannot be converted.
 */
private Number parse(Class sourceType, Class targetType, String value, NumberFormat format) {
    ParsePosition pos = new ParsePosition(0);
    Number parsedNumber = format.parse(value, pos);
    if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedNumber == null) {
        String msg = "Error converting from '" + toString(sourceType) + "' to '" + toString(targetType) + "'";
        if (format instanceof DecimalFormat) {
            msg += " using pattern '" + ((DecimalFormat) format).toPattern() + "'";
        }
        if (locale != null) {
            msg += " for locale=[" + locale + "]";
        }
        throw new ConversionException(msg);
    }
    return parsedNumber;
}