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

@Override
public Number parse(String text, ParsePosition pos) 

Source Link

Document

Parses text from a string to produce a Number .

Usage

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

public static BigDecimal convertToBigDecimal(String value) throws Exception {
    if (value == null || value.isEmpty()) {
        return null;
    }//from  www  .  jav a  2 s.  c o m
    try {
        DecimalFormat decfrm = getNumberFormat(DEFAULT_LOCALE);
        decfrm.setParseBigDecimal(true);
        ParsePosition pp = new ParsePosition(0);
        return (BigDecimal) decfrm.parse(value, pp);
    } catch (RuntimeException e) {
        throw new Exception("convertToBigDecimal:" + value + " failed:" + e.getMessage(), e);
    }
}

From source file:org.webguitoolkit.ui.controls.util.validation.PositiveNumberValidator.java

public void validate(String object) throws ValidationException {
    try {/*from   w  ww . j av a2 s  .  com*/
        // no mandatory field: empty means value zero.
        if (StringUtils.isEmpty(object)) {
            return;
        } else {
            DecimalFormat formatter;
            formatter = new DecimalFormat(pattern, new DecimalFormatSymbols(TextService.getLocale()));

            ParsePosition pos = new ParsePosition(0);
            Number num = formatter.parse(object, pos);

            if (num == null)
                throw new ValidationException(TextService.getString(
                        "converter.PositiveNumberValidator.message.conversion@Cannot convert into number."));
            if (pos.getIndex() < object.length()) {
                throw new ValidationException(TextService.getString(
                        "converter.PositiveNumberValidator.message.conversion@Cannot convert into number."));
            }

            Double f = new Double(num.doubleValue());
            if (f.doubleValue() < 0) {
                throw new ValidationException(TextService.getString(
                        "validator.PositiveNumberValidator.message@The entered number must be positive."));
            }
        }
    } catch (NumberFormatException e) {
        throw new ValidationException(TextService
                .getString("validator.PositiveNumberValidator.message.conversion@Cannot convert into number."));
    }
}

From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java

private BigDecimal strictParse(String value, Locale locale) throws ParseException {
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(locale);
    format.setParseBigDecimal(true);//from w w w.  j av a2  s  .  c  o  m
    value = value.trim();
    ParsePosition pos = new ParsePosition(0);
    BigDecimal number = (BigDecimal) format.parse(value, pos);
    boolean okay = pos.getIndex() == value.length() && pos.getErrorIndex() == -1;
    if (!okay)
        throw new ParseException("Could not parse '" + value + "' as a number", pos.getErrorIndex());
    return number;
}

From source file:org.totschnig.myexpenses.util.Utils.java

/**
 * <a href="http://www.ibm.com/developerworks/java/library/j-numberformat/">
 * http://www.ibm.com/developerworks/java/library/j-numberformat/</a>
 *
 * @param strFloat/*  w  ww  .  j av a  2 s  . co m*/
 *          parsed as float with the number format defined in the locale
 * @return the float retrieved from the string or null if parse did not
 *         succeed
 */
public static BigDecimal validateNumber(DecimalFormat df, String strFloat) {
    ParsePosition pp;
    pp = new ParsePosition(0);
    pp.setIndex(0);
    df.setParseBigDecimal(true);
    BigDecimal n = (BigDecimal) df.parse(strFloat, pp);
    if (strFloat.length() != pp.getIndex() || n == null) {
        return null;
    } else {
        return n;
    }
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler.java

public Object getTheValue(Field field, String[] paramValue, String desiredClassName) throws Exception {
    if (paramValue == null || paramValue.length == 0)
        return null;

    if (desiredClassName.equals("byte")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Byte((byte) 0);
        else//from   ww  w.  j  a  va  2s. co m
            return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals("short")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Short((short) 0);
        else
            return Short.decode(paramValue[0]);
    } else if (desiredClassName.equals("int")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Integer(0);
        else
            return Integer.decode(paramValue[0]);
    } else if (desiredClassName.equals("long")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Long(0L);
        else
            return Long.decode(paramValue[0]);
    } else if (desiredClassName.equals(Byte.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals(Short.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Short.decode(paramValue[0]);

    } else if (desiredClassName.equals(Integer.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Integer.decode(paramValue[0]);

    } else if (desiredClassName.equals(Long.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Long.decode(paramValue[0]);

    } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")
            || desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")
            || desiredClassName.equals(BigDecimal.class.getName())) {

        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();

        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(new Locale(LocaleManager.currentLang()));
        if (desiredClassName.equals(BigDecimal.class.getName()))
            df.setParseBigDecimal(true);
        String pattern = getFieldPattern(field);
        if (pattern != null && !"".equals(pattern)) {
            df.applyPattern(pattern);
        } else {
            df.applyPattern("###.##");
        }
        ParsePosition pp = new ParsePosition(0);
        Number num = df.parse(paramValue[0], pp);
        if (paramValue[0].length() != pp.getIndex() || num == null) {
            log.debug("Error on parsing value");
            throw new ParseException("Error parsing value", pp.getIndex());
        }

        if (desiredClassName.equals(BigDecimal.class.getName())) {
            return num;
        } else if (desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")) {
            return new Float(num.floatValue());
        } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")) {
            return new Double(num.doubleValue());
        }
    } else if (desiredClassName.equals(BigInteger.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return new BigInteger(paramValue[0]);

    }
    throw new IllegalArgumentException("Invalid class for NumericFieldHandler: " + desiredClassName);
}

From source file:org.pentaho.di.job.entries.zipfile.JobEntryZipFile.java

private int determineDepth(String depthString) throws KettleException {
    DecimalFormat df = new DecimalFormat("0");
    ParsePosition pp = new ParsePosition(0);
    df.setParseIntegerOnly(true);/* w  w w  . j a v  a2 s. com*/
    try {
        Number n = df.parse(depthString, pp);
        if (n == null) {
            return 1; // default
        }
        if (pp.getErrorIndex() == 0) {
            throw new KettleException("Unable to convert stored depth '" + depthString
                    + "' to depth at position " + pp.getErrorIndex());
        }
        return n.intValue();
    } catch (Exception e) {
        throw new KettleException("Unable to convert stored depth '" + depthString + "' to depth", e);
    }
}

From source file:org.orcid.frontend.web.controllers.FundingsController.java

/**
 * Transforms a string into a BigDecimal
 * /*www . j a  v  a2 s  .  c  om*/
 * @param amount
 * @param locale
 * @return a BigDecimal containing the given amount
 * @throws Exception
 *             if the amount cannot be correctly parse into a BigDecimal
 * */
public BigDecimal getAmountAsBigDecimal(String amount, Locale locale) throws Exception {
    try {
        ParsePosition parsePosition = new ParsePosition(0);
        DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale);
        DecimalFormatSymbols symbols = numberFormat.getDecimalFormatSymbols();
        /**
         * When spaces are allowed, the grouping separator is the character
         * 160, which is a non-breaking space So, lets change it so it uses
         * the default space as a separator
         * */
        if (symbols.getGroupingSeparator() == 160) {
            symbols.setGroupingSeparator(' ');
        }
        numberFormat.setDecimalFormatSymbols(symbols);
        Number number = numberFormat.parse(amount, parsePosition);
        if (number == null || parsePosition.getIndex() != amount.length()) {
            throw new Exception();
        }
        return new BigDecimal(number.toString());
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.orcid.core.manager.impl.OrcidProfileManagerImpl.java

/**
 * Replace the funding amount string into the desired format
 * /*from  w  w  w.  j  av  a  2s  . c o  m*/
 * @param updatedOrcidProfile
 *            The profile containing the new funding
 * */
private void setFundingAmountsWithTheCorrectFormat(OrcidProfile updatedOrcidProfile)
        throws IllegalArgumentException {
    FundingList fundings = updatedOrcidProfile.retrieveFundings();

    for (Funding funding : fundings.getFundings()) {
        // If the amount is not empty, update it
        if (funding.getAmount() != null && StringUtils.isNotBlank(funding.getAmount().getContent())) {
            String amount = funding.getAmount().getContent();
            Locale locale = localeManager.getLocale();
            ParsePosition parsePosition = new ParsePosition(0);
            DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale);
            DecimalFormatSymbols symbols = numberFormat.getDecimalFormatSymbols();
            /**
             * When spaces are allowed, the grouping separator is the
             * character 160, which is a non-breaking space So, lets change
             * it so it uses the default space as a separator
             * */
            if (symbols.getGroupingSeparator() == 160) {
                symbols.setGroupingSeparator(' ');
            }
            numberFormat.setDecimalFormatSymbols(symbols);
            Number number = numberFormat.parse(amount, parsePosition);
            String formattedAmount = number.toString();
            if (parsePosition.getIndex() != amount.length()) {
                double example = 1234567.89;
                NumberFormat numberFormatExample = NumberFormat.getNumberInstance(localeManager.getLocale());
                throw new IllegalArgumentException(
                        "The amount: " + amount + " doesn'n have the right format, it should use the format: "
                                + numberFormatExample.format(example));
            }
            funding.getAmount().setContent(formattedAmount);
        }
    }
}