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:org.openossad.util.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws OpenDESIGNERValueException {
    // 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);//from ww  w  . ja va 2s.com
    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 OpenDESIGNERValueException(message);
    }
}

From source file:org.jdto.mergers.DecimalFormatMerger.java

@Override
public Number restoreObject(String object, String[] params) {
    try {/*from w w w. j  a  v  a  2 s.  co  m*/
        if (object == null) {
            return null;
        }

        DecimalFormat format = getDecimalFormat(params);

        return format.parse(object);
    } catch (ParseException ex) {
        throw new IllegalArgumentException(ex);
    }
}

From source file:net.jofm.format.NumberFormat.java

@Override
protected Object doParse(String value, Class<?> destinationClazz) {
    Number result;//from   ww  w.j  a  v  a 2s.co  m
    try {
        if (StringUtils.isNotEmpty(format)) {
            DecimalFormat formatter = new DecimalFormat(format);
            result = formatter.parse(value);
        } else {
            result = Double.valueOf(value);
        }
    } catch (Exception pe) {
        throw new FixedMappingException(
                "Unable to parse the value '" + value + "' to number with format '" + format + "'");
    }

    return convert(result, destinationClazz);
}

From source file:org.pentaho.di.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);/*from w  w w .j  a v  a 2 s.c  o  m*/
    }
    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);
    }
}

From source file:com.wabacus.system.datatype.AbsNumberType.java

protected Number getNumber(String strvalue) {
    if (strvalue == null || strvalue.trim().equals(""))
        strvalue = "0";
    if (this.numberformat != null && !this.numberformat.trim().equals("")) {
        DecimalFormat df = new DecimalFormat(this.numberformat);
        Number n = 0;//from   w  ww. j  a va 2 s .c  o  m
        try {
            n = df.parse(strvalue.trim());
        } catch (ParseException e) {
            log.error(strvalue + "??" + this.numberformat + "?", e);
            n = 0;
        }
        return n;
    } else {
        return null;
    }
}

From source file:com.intuit.karate.Script.java

private static BigDecimal convertToBigDecimal(Object o) {
    DecimalFormat df = new DecimalFormat();
    df.setParseBigDecimal(true);//from   w  w w  .  ja va 2s  . c o  m
    try {
        return (BigDecimal) df.parse(o.toString());
    } catch (Exception e) {
        logger.warn("big decimal conversion failed: {}", e.getMessage());
        return null;
    }
}

From source file:org.gbif.ipt.struts2.converter.CoordinateFormatConverter.java

@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
    // The null value is needed to validate in EmlValidator.java class
    if (values[0].length() == 0) {
        return null;
    }/*from  w  ww . j  a va2  s . c  o m*/
    // The full name of the property which call the method contained in the Map context
    Object coordObject = context.get(ANGLE);
    // The latitude is validating in a range of doubles
    // validate coordinates in case the action context doesn't work properly.
    if (coordObject == null) {
        throw new TypeConversionException("Invalid decimal number: " + values[0]);
    } else {
        String coordinate = context.get(ANGLE).toString();
        // Assign the values of the range depending the property who calls the method.
        Range<Double> range;
        if (coordinate.equals(CoordinateUtils.LATITUDE)) {
            // The range of the latitude coordinate. (-90,90)
            range = Range.between(CoordinateUtils.MIN_LATITUDE, CoordinateUtils.MAX_LATITUDE);
        } else {
            // The range of the longitude coordinate. (-180,180)
            range = Range.between(CoordinateUtils.MIN_LONGITUDE, CoordinateUtils.MAX_LONGITUDE);
        }

        Double number;
        try {
            // Converts String to double if fails throws a NumberFormatException.
            // If the String contains a comma, a character, it throws the exception.
            number = Double.parseDouble(values[0]);
            // If the value is in the range, returns the double.
            if (range.contains(number)) {
                return number;
            } else {
                throw new TypeConversionException("Invalid decimal number: " + values[0]);
            }
        } catch (NumberFormatException e) {
            // Creating a pattern which will convert the comma to period
            // It will return a ParseException if the format was wrong.
            DecimalFormatSymbols symbols = new DecimalFormatSymbols();
            symbols.setDecimalSeparator(ALTERNATIVE_DECIMAL_SEPARATOR);
            DecimalFormat decimal = new DecimalFormat(DECIMAL_PATTERN, symbols);
            try {
                number = decimal.parse(values[0]).doubleValue();
                if (range.contains(number)) {
                    return number;
                } else {
                    throw new TypeConversionException("Invalid decimal number: " + values[0]);
                }
            } catch (ParseException e1) {
                throw new TypeConversionException("Invalid decimal number: " + values[0]);
            }
        }
    }
}

From source file:oracle.cubist.datasetBuilder.CubistDatasetBuilder.java

protected double parseDoubleFromCsv(String s) {
    /*try {/*  www.  j a  v a  2 s. c o  m*/
    double ret = Double.parseDouble(s);
    System.out.println("Safely parsed "+s+" into "+ret);
    return ret;
    } catch (NumberFormatException n) {     */
    log.trace("Double.parseDouble failed on " + s);
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator(',');
    DecimalFormat dcf = new DecimalFormat();
    dcf.setDecimalFormatSymbols(symbols);
    try {
        double ret = dcf.parse(s).doubleValue();
        log.trace("Parsed " + s + " into " + dcf.parse(s).doubleValue());
        return ret;
    } catch (ParseException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        throw new RuntimeException("ciao");
    }
    //}
}

From source file:de.jfachwert.pruefung.NumberValidator.java

/**
 * Normalisiert einen String, sodass er zur Generierung einer Zahl
 * herangezogen werden kann.//ww w .  jav a 2  s .  c o m
 * 
 * @param value z.B. "1,234.5"
 * @return normalisiert, z.B. "1234.5"
 */
public String normalize(String value) {
    if (!value.matches("[\\d,.]+([eE]\\d+)?")) {
        throw new InvalidValueException(value, NUMBER);
    }
    Locale locale = guessLocale(value);
    DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(locale);
    df.setParseBigDecimal(true);
    try {
        return df.parse(value).toString();
    } catch (ParseException ex) {
        throw new InvalidValueException(value, NUMBER, ex);
    }
}

From source file:org.dashbuilder.dataprovider.backend.csv.CSVParser.java

protected ColumnType calculateType(String columnId, String value) {
    DataColumn column = dataSetDef.getDataSet().getColumnById(columnId);
    if (column != null)
        return column.getColumnType();

    try {/*w w w .ja va  2s  .  co  m*/
        DateFormat dateFormat = getDateFormat(columnId);
        dateFormat.parse(value);
        return ColumnType.DATE;
    } catch (Exception e) {
        try {
            DecimalFormat numberFormat = getNumberFormat(columnId);
            numberFormat.parse(value);
            return ColumnType.NUMBER;
        } catch (Exception ee) {
            return ColumnType.LABEL;
        }
    }
}