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.apache.cordova.core.Globalization.java

private JSONObject getStringToNumber(JSONArray options) throws GlobalizationError {
    JSONObject obj = new JSONObject();
    Number value;/*from w  w  w  .  j  a  v  a2  s . co m*/
    try {
        DecimalFormat fmt = getNumberFormatInstance(options); //returns Decimal/Currency/Percent instance
        value = fmt.parse((String) options.getJSONObject(0).get(NUMBERSTRING));
        return obj.put("value", value);
    } catch (Exception ge) {
        throw new GlobalizationError(GlobalizationError.PARSING_ERROR);
    }
}

From source file:com.qcadoo.mes.deliveries.DeliveriesServiceImpl.java

@Override
public BigDecimal getBigDecimalFromField(final FieldComponent fieldComponent, final Locale locale) {
    Object value = fieldComponent.getFieldValue();

    try {// w w w  . j  a  va  2s  . c om
        DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(locale);
        format.setParseBigDecimal(true);

        return new BigDecimal(format.parse(value.toString()).doubleValue());
    } catch (ParseException e) {
        return null;
    }
}

From source file:org.enerj.apache.commons.beanutils.locale.converters.DecimalLocaleConverter.java

/**
 * Convert the specified locale-sensitive input object into an output object of the
 * specified type.//from   w ww .j  a v a  2 s .c  o  m
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the convertion
 *
 * @exception ConversionException if conversion cannot be performed
 *  successfully
 */
protected Object parse(Object value, String pattern) throws ParseException {
    // DecimalFormat is not thread safe so best to construct one each time
    DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(locale);
    // if some constructors default pattern to null, it makes only sense to handle null pattern gracefully
    if (pattern != null) {
        if (locPattern) {
            formatter.applyLocalizedPattern(pattern);
        } else {
            formatter.applyPattern(pattern);
        }
    } else {
        log.warn("No pattern provided, using default.");
    }

    return formatter.parse((String) value);
}

From source file:javadz.beanutils.locale.converters.DecimalLocaleConverter.java

/**
 * Convert the specified locale-sensitive input object into an output 
 * object of the specified type./*from   ww w . j  av a 2  s .co m*/
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the convertion
 * @return The converted value
 *
 * @exception org.apache.commons.beanutils.ConversionException if conversion
 * cannot be performed successfully
 * @throws ParseException if an error occurs parsing a String to a Number
 */
protected Object parse(Object value, String pattern) throws ParseException {

    if (value instanceof Number) {
        return value;
    }

    // Note that despite the ambiguous "getInstance" name, and despite the
    // fact that objects returned from this method have the same toString
    // representation, each call to getInstance actually returns a new
    // object.
    DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(locale);

    // if some constructors default pattern to null, it makes only sense 
    // to handle null pattern gracefully
    if (pattern != null) {
        if (locPattern) {
            formatter.applyLocalizedPattern(pattern);
        } else {
            formatter.applyPattern(pattern);
        }
    } else {
        log.debug("No pattern provided, using default.");
    }

    return formatter.parse((String) value);
}

From source file:org.efaps.esjp.accounting.transaction.Calculation_Base.java

/**
 * Gets the JS 4 exchange rate.//from ww  w .  java2s.c  o m
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _parameterClone the parameter clone
 * @param _postfix the postfix
 * @return the JS 4 exchange rate
 * @throws EFapsException on error
 */
protected StringBuilder getJS4ExchangeRate(final Parameter _parameter, final Parameter _parameterClone,
        final String _postfix) throws EFapsException {
    final StringBuilder ret = new StringBuilder();
    try {
        final String[] amounts = _parameter.getParameterValues("amount_" + _postfix);
        final String[] currencies = _parameter.getParameterValues("rateCurrencyLink_" + _postfix);
        final String[] selected = _parameter.getParameterValues("posSelect_" + _postfix);

        final ExchangeConfig exConf = getExchangeConfig(_parameter, null);

        for (int i = 0; i < selected.length; i++) {
            if (BooleanUtils.toBoolean(selected[i])) {
                final DateTime date;
                switch (exConf) {
                case DOCDATEPURCHASE:
                case DOCDATESALE:
                    final Instance docInst = Instance
                            .get(_parameter.getParameterValues("docLink_" + _postfix)[i]);
                    if (InstanceUtils.isValid(docInst)) {
                        final PrintQuery print = CachedPrintQuery.get4Request(docInst);
                        print.addAttribute(CIERP.DocumentAbstract.Date);
                        print.execute();
                        date = print.getAttribute(CIERP.DocumentAbstract.Date);
                    } else {
                        final String dateStr = _parameter.getParameterValue("date_eFapsDate");
                        date = DateUtil.getDateFromParameter(dateStr);
                    }
                    break;
                case TRANSDATESALE:
                case TRANSDATEPURCHASE:
                default:
                    final String dateStr = _parameter.getParameterValue("date_eFapsDate");
                    date = DateUtil.getDateFromParameter(dateStr);
                    break;
                }

                final boolean sale = ExchangeConfig.TRANSDATESALE.equals(exConf)
                        || ExchangeConfig.DOCDATESALE.equals(exConf);
                final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);

                final RateInfo rate = evaluateRate(_parameter, periodInstance, date,
                        Instance.get(CIERP.Currency.getType(), currencies[i]));
                final DecimalFormat rateFormater = sale ? rate.getFormatter().getFrmt4SaleRateUI()
                        : rate.getFormatter().getFrmt4RateUI();
                final BigDecimal amountRate = amounts[i].isEmpty() ? BigDecimal.ZERO
                        : (BigDecimal) rateFormater.parse(amounts[i]);

                final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();

                final String rateStr = sale ? rate.getSaleRateUIFrmt() : rate.getRateUIFrmt();
                final String rateInStr = "" + rate.isInvert();
                final String amountStr = formater.format(amountRate.setScale(12)
                        .divide(sale ? rate.getSaleRate() : rate.getRate(), BigDecimal.ROUND_HALF_UP));

                ret.append(getSetFieldValue(i, "rate_" + _postfix, rateStr))
                        .append(getSetFieldValue(i, "rate_" + _postfix + RateUI.INVERTEDSUFFIX, rateInStr))
                        .append(getSetFieldValue(i, "amountRate_" + _postfix, amountStr));

                ParameterUtil.setParameterValue(_parameterClone, "rate_" + _postfix, i, rateStr);
                ParameterUtil.setParameterValue(_parameterClone, "rate_" + _postfix + RateUI.INVERTEDSUFFIX, i,
                        rateInStr);
                ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + _postfix, i, amountStr);
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java

/**
 * Method is executed on update trigger for the amount field in the debit
 * and credit table inside the transaction form.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return list for update trigger/*from  www  . j  a v  a  2s. c  o m*/
 * @throws EFapsException on error
 */
public Return update4Amount(final Parameter _parameter) throws EFapsException {
    final Return retVal = new Return();
    try {
        final String postfix = getProperty(_parameter, "TypePostfix");
        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);
        final String[] rates = _parameter.getParameterValues("rate_" + postfix);
        final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX);

        final int pos = getSelectedRow(_parameter);
        final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8);
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);
        BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ZERO : (BigDecimal) rateFormater.parse(rates[pos]);
        final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]);
        if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) {
            rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP);
        }
        final List<Map<String, String>> list = new ArrayList<>();
        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);

        final BigDecimal sum = getSum4UI(_parameter, postfix, null, null);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final Map<String, String> map = new HashMap<>();
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix,
                formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);
        retVal.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Amount.ParseException", e);
    }
    return retVal;
}

From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java

/**
 * Method is executed on update trigger for the rate field in the debit
 * and credit table inside the transaction form.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return list for update trigger/*from w w w  . j  a v a2 s  .c om*/
 * @throws EFapsException on error
 */
public Return update4Rate(final Parameter _parameter) throws EFapsException {
    final Return retVal = new Return();

    try {
        final String postfix = getProperty(_parameter, "TypePostfix");

        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);
        final String[] rates = _parameter.getParameterValues("rate_" + postfix);
        final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX);

        final int pos = getSelectedRow(_parameter);
        final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8);
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);
        BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ONE : (BigDecimal) rateFormater.parse(rates[pos]);
        final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]);
        if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) {
            rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP);
        }
        final List<Map<String, String>> list = new ArrayList<>();
        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);

        final BigDecimal sum = getSum4UI(_parameter, postfix, null, null);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final Map<String, String> map = new HashMap<>();
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix,
                formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);

        retVal.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Rate.ParseException", e);
    }
    return retVal;
}

From source file:org.jbpm.designer.web.server.SimulationServlet.java

private double adjustDouble(double in) throws ParseException {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    String formattedValue = twoDForm.format(in);
    return twoDForm.parse(formattedValue).doubleValue();
}

From source file:org.jbpm.designer.web.server.SimulationServlet.java

private double adjustToSecs(double in) throws ParseException {
    if (in > 0) {
        in = in / 1000;//from w w  w  . j  a  v  a  2s . com
    }
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    String formattedValue = twoDForm.format(in);
    return twoDForm.parse(formattedValue).doubleValue();
}

From source file:org.jbpm.designer.web.server.SimulationServlet.java

private double adjustToBaseTimeUnit(double in, int baseTime) throws ParseException {
    if (in > 0) {
        if (baseTime == 1) {
            in = in / 1000;/*from   w  ww .  jav a  2  s .  co m*/
        } else if (baseTime == 2) {
            in = in / (1000 * 60);
        } else if (baseTime == 3) {
            in = in / (1000 * 60 * 60);
        } else if (baseTime == 4) {
            in = in / (1000 * 60 * 60 * 24);
        } else if (baseTime == 5) {
            in = in / (1000 * 60 * 60 * 24 * 365);
        }
    }

    DecimalFormat twoDForm = new DecimalFormat("#.##");
    String formattedValue = twoDForm.format(in);
    return twoDForm.parse(formattedValue).doubleValue();
}