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:javadz.beanutils.converters.NumberConverter.java

/**
 * Convert a String into a <code>Number</code> object.
 * @param sourceType TODO/*from   w w w .  ja v  a 2  s.co 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 + "]";
        }
        if (log().isDebugEnabled()) {
            log().debug("    " + msg);
        }
        throw new ConversionException(msg);
    }
    return parsedNumber;
}

From source file:org.apache.ambari.scom.SQLPropertyProvider.java

private Map<MetricDefinition, List<DataPoint>> getMetric(Set<MetricDefinition> metricDefinitionSet,
        Statement statement) throws SystemException {
    Map<MetricDefinition, List<DataPoint>> results = new HashMap<MetricDefinition, List<DataPoint>>();
    try {//from   ww  w .  j a  v  a  2  s . c  o m
        StringBuilder query = new StringBuilder();
        Set<String> recordTypeContexts = new HashSet<String>();
        Set<String> recordTypeNamess = new HashSet<String>();
        Set<String> tagPairsPatterns = new HashSet<String>();
        Set<String> nodeNames = new HashSet<String>();
        Set<String> serviceNames = new HashSet<String>();
        Set<String> metricNames = new HashSet<String>();
        long startTime = 0, endTime = 0;
        for (MetricDefinition metricDefinition : metricDefinitionSet) {
            if (metricDefinition.getRecordTypeContext() == null || metricDefinition.getRecordTypeName() == null
                    || metricDefinition.getNodeName() == null) {
                continue;
            }

            recordTypeContexts.add(metricDefinition.getRecordTypeContext());
            recordTypeNamess.add(metricDefinition.getRecordTypeName());
            tagPairsPatterns.add(metricDefinition.getTagPairsPattern());
            nodeNames.add(metricDefinition.getNodeName());
            serviceNames.add(metricDefinition.getServiceName());
            metricNames.add(metricDefinition.getMetricName());
            startTime = metricDefinition.getStartTime();
            endTime = metricDefinition.getEndTime();
        }

        for (String tagPairsPattern : tagPairsPatterns) {
            if (query.length() != 0) {
                query.append("\nUNION\n");
            }
            query.append(String.format(GET_METRICS_STATEMENT,
                    "'" + StringUtils.join(recordTypeContexts, "','") + "'",
                    "'" + StringUtils.join(recordTypeNamess, "','") + "'", "'%" + tagPairsPattern + "%'",
                    "'" + StringUtils.join(nodeNames, "','") + "'",
                    "'" + StringUtils.join(serviceNames, "','") + "'", startTime, endTime,
                    "'" + StringUtils.join(metricNames, "','") + "'"));
        }

        ResultSet rs = null;
        if (query.length() != 0) {
            rs = statement.executeQuery(query.toString());
        }

        if (rs != null) {
            //(RecordTimeStamp bigint, MetricValue NVARCHAR(512))
            while (rs.next()) {
                MetricDefinition metricDefinition = new MetricDefinition(rs.getString("RecordTypeContext"),
                        rs.getString("RecordTypeName"), rs.getString("TagPairs"), rs.getString("MetricName"),
                        rs.getString("ServiceName"), rs.getString("NodeName"));
                ParsePosition parsePosition = new ParsePosition(0);
                NumberFormat numberFormat = NumberFormat.getInstance();
                Number parsedNumber = numberFormat.parse(rs.getNString("MetricValue"), parsePosition);
                if (results.containsKey(metricDefinition)) {
                    results.get(metricDefinition)
                            .add(new DataPoint(rs.getLong("RecordTimeStamp"), parsedNumber));
                } else {
                    List<DataPoint> dataPoints = new ArrayList<DataPoint>();
                    dataPoints.add(new DataPoint(rs.getLong("RecordTimeStamp"), parsedNumber));
                    results.put(metricDefinition, dataPoints);
                }
            }
        }
    } catch (SQLException e) {
        throw new SystemException("Error during getMetric call : caught exception - ", e);
    }
    return results;
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private Object doConvertToNumber(Map<String, Object> context, Object value, Class toType) {
    if (value instanceof String) {
        if (toType == BigDecimal.class) {
            return new BigDecimal((String) value);
        } else if (toType == BigInteger.class) {
            return new BigInteger((String) value);
        } else if (toType.isPrimitive()) {
            Object convertedValue = super.convertValue(context, value, toType);
            String stringValue = (String) value;
            if (!isInRange((Number) convertedValue, stringValue, toType))
                throw new XWorkException("Overflow or underflow casting: \"" + stringValue + "\" into class "
                        + convertedValue.getClass().getName());

            return convertedValue;
        } else {// w  w w .j  ava  2s  .  co  m
            String stringValue = (String) value;
            if (!toType.isPrimitive() && (stringValue == null || stringValue.length() == 0)) {
                return null;
            }
            NumberFormat numFormat = NumberFormat.getInstance(getLocale(context));
            ParsePosition parsePos = new ParsePosition(0);
            if (isIntegerType(toType)) {
                numFormat.setParseIntegerOnly(true);
            }
            numFormat.setGroupingUsed(true);
            Number number = numFormat.parse(stringValue, parsePos);

            if (parsePos.getIndex() != stringValue.length()) {
                throw new XWorkException(
                        "Unparseable number: \"" + stringValue + "\" at position " + parsePos.getIndex());
            } else {
                if (!isInRange(number, stringValue, toType))
                    throw new XWorkException("Overflow or underflow casting: \"" + stringValue
                            + "\" into class " + number.getClass().getName());

                value = super.convertValue(context, number, toType);
            }
        }
    } else if (value instanceof Object[]) {
        Object[] objArray = (Object[]) value;

        if (objArray.length == 1) {
            return doConvertToNumber(context, objArray[0], toType);
        }
    }

    // pass it through DefaultTypeConverter
    return super.convertValue(context, value, toType);
}

From source file:cfa.vo.sed.science.stacker.SedStackerFrame.java

private 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:net.sf.morph.transform.converters.TextToNumberConverter.java

/**
 * {@inheritDoc}//w  w  w . j a  v a2  s.  c  o m
 */
protected Object convertImpl(Class destinationClass, Object source, Locale locale) throws Exception {

    if (ObjectUtils.isEmpty(source)) {
        return null;
    }
    // convert the source to a String
    String string = (String) getTextConverter().convert(String.class, source, locale);

    //         // if a custom numberFormat has been specified, ues that for the
    //         // conversion
    //         if (numberFormat != null) {
    //            Number number;
    //            synchronized (numberFormat) {
    //               number = numberFormat.parse(string);
    //            }
    //
    //            // convert the number to the destination class requested
    //            return getNumberConverter().convert(destinationClass, number,
    //               locale);
    //         }

    StringBuffer charactersToParse =
            // remove characters that should be ignored, such as currency symbols
            // when currency handling is set to CURRENCY_IGNORE
            removeIgnoredCharacters(string, locale);

    // keep track of whether the conversion result needs to be negated
    // before it is returned
    boolean negate = handleParenthesesNegation(charactersToParse, locale);
    negate = negate || handleNegativeSignNegation(charactersToParse, locale);

    NumberFormat format = null;
    ParsePosition position = null;
    Number number = null;
    Object returnVal = null;
    String stringToParse = charactersToParse.toString();

    // could not get this to work for some reason
    //         // try to do the conversion assuming the source is a currency value
    //         format = NumberFormat.getCurrencyInstance(locale);
    //         position = new ParsePosition(0);
    //         number = format.parse(stringWithoutIgnoredSymbolsStr, position);
    //         if (isParseSuccessful(stringWithoutIgnoredSymbolsStr, position)) {
    //            // convert the number to the destination class requested
    //            returnVal = getNumberConverter().convert(destinationClass, number,
    //               locale);
    //            if (logger.isDebugEnabled()) {
    //               logger.debug("Successfully parsed '" + source + "' as a currency value of " + returnVal);
    //            }
    //            return returnVal;
    //         }
    //         else {
    //            if (logger.isDebugEnabled()) {
    //               logger.debug("Could not perform conversion of '" + source + "' by treating the source as a currency value");
    //            }
    //         }

    // try to do the conversion to decimal assuming the source is a
    // percentage
    if (getPercentageHandling() == PERCENTAGE_CONVERT_TO_DECIMAL) {
        format = NumberFormat.getPercentInstance(locale);
        position = new ParsePosition(0);
        number = format.parse(stringToParse, position);
        if (isParseSuccessful(stringToParse, position)) {
            // negate the number if needed
            returnVal = negateIfNecessary(number, negate, locale);
            // convert the number to the destination class requested
            returnVal = getNumberConverter().convert(destinationClass, returnVal, locale);
            if (logger.isDebugEnabled()) {
                logger.debug("Successfully parsed '" + source + "' as a percentage with value " + returnVal);
            }
            return returnVal;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Could not perform conversion of '" + source + "' by treating the source as a percentage");
        }
    }

    // try to do the conversion as a regular number
    format = NumberFormat.getInstance(locale);
    position = new ParsePosition(0);
    number = format.parse(stringToParse, position);
    if (isParseSuccessful(stringToParse, position)) {
        // negate the number if needed
        returnVal = negateIfNecessary(number, negate, locale);
        // convert the number to the destination class requested
        returnVal = getNumberConverter().convert(destinationClass, returnVal, locale);
        if (logger.isDebugEnabled()) {
            logger.debug("Successfully parsed '" + source + "' as a number or currency value of " + returnVal);
        }
        return returnVal;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Could not perform conversion of '" + source
                + "' by treating the source as a regular number or currency value");
    }

    //         // if the first character of the string is a currency symbol
    //         if (Character.getType(stringWithoutIgnoredSymbolsStr.charAt(0)) == Character.CURRENCY_SYMBOL) {
    //            // try doing the conversion as a regular number by stripping off the first character
    //            format = NumberFormat.getInstance(locale);
    //            position = new ParsePosition(1);
    //            number = format.parse(stringWithoutIgnoredSymbolsStr, position);
    //            if (isParseSuccessful(stringWithoutIgnoredSymbolsStr, position)) {
    //               // convert the number to the destination class requested
    //               return getNumberConverter().convert(destinationClass, number,
    //                  locale);
    //            }
    //            if (logger.isDebugEnabled()) {
    //               logger.debug("Could not perform conversion of '" + source + "' by stripping the first character and treating as a normal number");
    //            }
    //         }

    throw new TransformationException(destinationClass, source);
}