Example usage for java.text DecimalFormat parse

List of usage examples for java.text DecimalFormat parse

Introduction

In this page you can find the example usage for java.text DecimalFormat 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:de.jlo.talendcomp.json.TypeUtil.java

public static Double convertToDouble(String value) throws Exception {
    if (value == null || value.isEmpty()) {
        return null;
    }//from   w ww . j av  a 2  s. c  om
    DecimalFormat decfrm = getNumberFormat(DEFAULT_LOCALE);
    decfrm.setParseBigDecimal(false);
    return decfrm.parse(value).doubleValue();
}

From source file:de.jlo.talendcomp.json.TypeUtil.java

public static Integer convertToInteger(String value) throws Exception {
    if (value == null || value.isEmpty()) {
        return null;
    }/*from  w  w w.  j a  v  a 2  s .  co  m*/
    DecimalFormat decfrm = getNumberFormat(DEFAULT_LOCALE);
    decfrm.setParseBigDecimal(false);
    return decfrm.parse(value).intValue();
}

From source file:com.insightaction.util.DataLoader.java

private static BigDecimal getBigDecimal(String value) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setGroupingSeparator(',');
    symbols.setDecimalSeparator('.');
    String pattern = "#,##0.0#";
    DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
    decimalFormat.setParseBigDecimal(true);

    BigDecimal bigDecimal = null;
    try {//  ww  w  .j a va  2 s. com
        bigDecimal = (BigDecimal) decimalFormat.parse(value);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return bigDecimal;
}

From source file:at.asitplus.regkassen.core.base.util.CashBoxUtils.java

/**
 * get double value from arbitrary String represent a double (0,00) or (0.00)
 *
 * @param taxSetValue double value as String
 * @return double value//from   www  .j a va2s .  c  o  m
 * @throws Exception
 */
public static double getDoubleFromTaxSet(String taxSetValue) throws Exception {
    //try format ("0,00")
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
    DecimalFormat decimalFormat = (DecimalFormat) nf;
    Exception parseException;
    try {
        return decimalFormat.parse(taxSetValue).doubleValue();
    } catch (ParseException ignored) {
    }
    //if Austrian/German format fail, try US format (0.00)
    nf = NumberFormat.getNumberInstance(Locale.US);
    decimalFormat = (DecimalFormat) nf;
    try {
        return decimalFormat.parse(taxSetValue).doubleValue();
    } catch (ParseException e) {
        parseException = e;
    }
    throw parseException;
}

From source file:org.saiku.reporting.backend.component.ReportContentUtil.java

private static Object convert(final ParameterContext context, final ParameterDefinitionEntry parameter,
        final Class targetType, final Object rawValue) throws ReportProcessingException {
    if (targetType == null) {
        throw new NullPointerException();
    }/* w  w w.j a v  a  2s. c  o  m*/

    if (rawValue == null) {
        return null;
    }
    if (targetType.isInstance(rawValue)) {
        return rawValue;
    }

    //TODO:    
    //    if (targetType.isAssignableFrom(TableModel.class) && IPentahoResultSet.class.isAssignableFrom(rawValue.getClass()))
    //    {
    //      // wrap IPentahoResultSet to simulate TableModel
    //      return new PentahoTableModel((IPentahoResultSet) rawValue);
    //    }

    final String valueAsString = String.valueOf(rawValue);
    if (StringUtils.isEmpty(valueAsString)) {
        // none of the converters accept empty strings as valid input. So we can return null instead.
        return null;
    }

    if (targetType.equals(Timestamp.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Timestamp(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(Time.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Time(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(java.sql.Date.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new java.sql.Date(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(Date.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Date(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    }

    final String dataFormat = parameter.getParameterAttribute(ParameterAttributeNames.Core.NAMESPACE,
            ParameterAttributeNames.Core.DATA_FORMAT, context);
    if (dataFormat != null) {
        try {
            if (Number.class.isAssignableFrom(targetType)) {
                final DecimalFormat format = new DecimalFormat(dataFormat,
                        new DecimalFormatSymbols(Locale.getDefault()));
                format.setParseBigDecimal(true);
                final Number number = format.parse(valueAsString);
                final String asText = ConverterRegistry.toAttributeValue(number);
                return ConverterRegistry.toPropertyValue(asText, targetType);
            } else if (Date.class.isAssignableFrom(targetType)) {
                final SimpleDateFormat format = new SimpleDateFormat(dataFormat,
                        new DateFormatSymbols(Locale.getDefault()));
                format.setLenient(false);
                final Date number = format.parse(valueAsString);
                final String asText = ConverterRegistry.toAttributeValue(number);
                return ConverterRegistry.toPropertyValue(asText, targetType);
            }
        } catch (Exception e) {
            // again, ignore it .
        }
    }

    final ValueConverter valueConverter = ConverterRegistry.getInstance().getValueConverter(targetType);
    if (valueConverter != null) {
        try {
            return valueConverter.toPropertyValue(valueAsString);
        } catch (BeanException e) {
            throw new ReportProcessingException(
                    "ReportPlugin.unableToConvertParameter " + parameter.getName() + " " + valueAsString); //$NON-NLS-1$
        }
    }
    return rawValue;
}

From source file:org.pentaho.reporting.platform.plugin.ReportContentUtil.java

private static Object convert(final ParameterContext context, final ParameterDefinitionEntry parameter,
        final Class targetType, final Object rawValue) throws ReportProcessingException {
    if (targetType == null) {
        throw new NullPointerException();
    }//from  ww  w . ja  va 2s .  co m

    if (rawValue == null) {
        return null;
    }
    if (targetType.isInstance(rawValue)) {
        return rawValue;
    }

    if (targetType.isAssignableFrom(TableModel.class)
            && IPentahoResultSet.class.isAssignableFrom(rawValue.getClass())) {
        // wrap IPentahoResultSet to simulate TableModel
        return new PentahoTableModel((IPentahoResultSet) rawValue);
    }

    final String valueAsString = String.valueOf(rawValue);
    if (StringUtils.isEmpty(valueAsString)) {
        // none of the converters accept empty strings as valid input. So we can return null instead.
        return null;
    }

    if (targetType.equals(Timestamp.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Timestamp(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(Time.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Time(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(java.sql.Date.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new java.sql.Date(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(Date.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Date(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    }

    final String dataFormat = parameter.getParameterAttribute(ParameterAttributeNames.Core.NAMESPACE,
            ParameterAttributeNames.Core.DATA_FORMAT, context);
    if (dataFormat != null) {
        try {
            if (Number.class.isAssignableFrom(targetType)) {
                final DecimalFormat format = new DecimalFormat(dataFormat,
                        new DecimalFormatSymbols(LocaleHelper.getLocale()));
                format.setParseBigDecimal(true);
                final Number number = format.parse(valueAsString);
                final String asText = ConverterRegistry.toAttributeValue(number);
                return ConverterRegistry.toPropertyValue(asText, targetType);
            } else if (Date.class.isAssignableFrom(targetType)) {
                final SimpleDateFormat format = new SimpleDateFormat(dataFormat,
                        new DateFormatSymbols(LocaleHelper.getLocale()));
                format.setLenient(false);
                final Date number = format.parse(valueAsString);
                final String asText = ConverterRegistry.toAttributeValue(number);
                return ConverterRegistry.toPropertyValue(asText, targetType);
            }
        } catch (Exception e) {
            // again, ignore it .
        }
    }

    final ValueConverter valueConverter = ConverterRegistry.getInstance().getValueConverter(targetType);
    if (valueConverter != null) {
        try {
            return valueConverter.toPropertyValue(valueAsString);
        } catch (BeanException e) {
            throw new ReportProcessingException(Messages.getInstance()
                    .getString("ReportPlugin.unableToConvertParameter", parameter.getName(), valueAsString)); //$NON-NLS-1$
        }
    }
    return rawValue;
}

From source file:com.prowidesoftware.swift.utils.SwiftFormatUtils.java

/**
 * Parses a value into a java Number (BigDecimal) using the comma for decimal separator.
 * @param amount to parse/* w  w  w.j a  v  a 2s .c  om*/
 * @return Number of the parsed amount or <code>null</code> if the number could not be parsed
 */
public static Number getNumber(final String amount) {
    Number number = null;
    if (amount != null) {
        try {
            final DecimalFormatSymbols symbols = new DecimalFormatSymbols();
            symbols.setDecimalSeparator(',');
            final DecimalFormat df = new DecimalFormat("00.##", symbols);
            df.setParseBigDecimal(true);
            number = df.parse(amount);
        } catch (final ParseException e) {
            log.log(java.util.logging.Level.WARNING, "Error parsing number", e);
        }
    }
    return number;
}

From source file:org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement.java

private static String getNextForMonth(Class<? extends SQLElement> clazz, Date d) {

    final SQLTable table = Configuration.getInstance().getDirectory().getElement(clazz).getTable();
    final SQLRow rowNum = TABLE_NUM.getRow(2);
    final String s = map.get(clazz);
    final String pattern = rowNum.getString(s + FORMAT);
    final Tuple2<String, String> prefixSuffix = getPrefixAndSuffix(pattern, d);
    final String prefix = prefixSuffix.get0();
    final String suffix = prefixSuffix.get1();

    Where w = new Where(table.getField("NUMERO"), "LIKE", "%" + prefix + "%");
    final SQLSelect sel = new SQLSelect();
    sel.addSelect(table.getField("NUMERO"));
    sel.addSelect(table.getKey());// ww  w. j  av  a2 s .com

    sel.setWhere(w);
    SQLDataSource source = Configuration.getInstance().getBase().getDataSource();

    final ResultSetHandler createFromSelect = SQLRowListRSH.createFromSelect(sel);

    final List<SQLRow> l = (List<SQLRow>) source.execute(sel.asString(),
            new IResultSetHandler(createFromSelect, false));

    final String decimalPattern = "'" + prefix + "'" + suffix;
    final DecimalFormat format = new DecimalFormat(decimalPattern);
    int value = 0;
    for (SQLRow sqlRow : l) {

        final String numero = sqlRow.getString("NUMERO");
        try {

            final Number n = format.parse(numero);
            value = Math.max(value, n.intValue());
        } catch (ParseException exn) {
            System.err.println("NumerotationAutoSQLElement.getNextForMonth(): warning: unable to parse "
                    + numero + " with pattern " + decimalPattern + " row:" + sqlRow);
            exn.printStackTrace();
        }
    }
    final String result = format.format(value + 1);
    System.err.println("NumerotationAutoSQLElement.getNextForMonth(): " + result);
    return result;
}

From source file:com.jkoolcloud.tnt4j.streams.utils.NumericFormatter.java

/**
 * Formats the specified object using the defined pattern, or using the default numeric formatting if no pattern was
 * defined.//from   ww w .j  av  a2 s.  c  om
 *
 * @param formatter
 *            formatter object to apply to value
 * @param radix
 *            the radix to use while parsing numeric strings
 * @param value
 *            value to convert
 * @param scale
 *            value to multiply the formatted value by
 *
 * @return formatted value of field in required internal data type
 *
 * @throws ParseException
 *             if an error parsing the specified value based on the field definition (e.g. does not match defined
 *             pattern, etc.)
 */
private static Number parse(DecimalFormat formatter, int radix, Object value, Number scale)
        throws ParseException {
    if (value == null) {
        return null;
    }
    if (scale == null) {
        scale = 1.0;
    }
    try {
        Number numValue = null;
        if (formatter == null && value instanceof String) {
            String strValue = (String) value;
            if (strValue.startsWith("0x") || strValue.startsWith("0X")) { // NON-NLS
                numValue = Long.parseLong(strValue.substring(2), 16);
            }
        }
        if (numValue == null) {
            if (formatter != null) {
                numValue = formatter.parse(value.toString());
            } else if (radix != 10) {
                numValue = Long.parseLong(value.toString(), radix);
            } else {
                numValue = value instanceof Number ? (Number) value : Double.valueOf(value.toString());
            }
        }
        Number scaledValue = numValue.doubleValue() * scale.doubleValue();
        return Utils.castNumber(scaledValue, numValue.getClass());
    } catch (NumberFormatException nfe) {
        throw new ParseException(nfe.getLocalizedMessage(), 0);
    }
}

From source file:com.panet.imeta.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws KettleValueException {
    // 0 : pattern
    // 1 : Decimal separator
    // 2 : Grouping separator
    // 3 : Currency symbol

    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat) nf;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    if (!Const.isEmpty(pattern))
        df.applyPattern(pattern);/*w w w  .ja  v a2  s  .c  om*/
    if (!Const.isEmpty(decimal))
        dfs.setDecimalSeparator(decimal.charAt(0));
    if (!Const.isEmpty(grouping))
        dfs.setGroupingSeparator(grouping.charAt(0));
    if (!Const.isEmpty(currency))
        dfs.setCurrencySymbol(currency);
    try {
        df.setDecimalFormatSymbols(dfs);
        return df.parse(value).doubleValue();
    } catch (Exception e) {
        String message = "Couldn't convert string to number " + e.toString();
        if (!isEmpty(pattern))
            message += " pattern=" + pattern;
        if (!isEmpty(decimal))
            message += " decimal=" + decimal;
        if (!isEmpty(grouping))
            message += " grouping=" + grouping.charAt(0);
        if (!isEmpty(currency))
            message += " currency=" + currency;
        throw new KettleValueException(message);
    }
}