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.efaps.esjp.accounting.transaction.Calculation_Base.java

/**
 * Gets the JS for fill up.//  w ww  . j a  v  a2  s. c o m
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _parameterClone the parameter clone
 * @return the JS 4 fill up
 * @throws EFapsException on error
 */
protected StringBuilder getJS4FillUp(final Parameter _parameter, final Parameter _parameterClone)
        throws EFapsException {
    final StringBuilder ret = new StringBuilder();
    try {
        String postfix = null;
        boolean eval = true;
        while (eval) {
            eval = postfix == null;
            postfix = postfix == null ? "Debit" : "Credit";
            final String[] selected = _parameter.getParameterValues("posSelect_" + postfix);
            if (ArrayUtils.isNotEmpty(selected)) {
                for (int i = 0; i < selected.length; i++) {
                    if (BooleanUtils.toBoolean(selected[i])) {
                        eval = false;
                        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();

                        final Instance periodInst = new Period().evaluateCurrentPeriod(_parameterClone);
                        final Instance periodCurrenycInstance = new Period().getCurrency(periodInst)
                                .getInstance();

                        final BigDecimal sumDebit = getSum4UI(_parameter, "Debit", null, null);
                        final BigDecimal sumCredit = getSum4UI(_parameter, "Credit", null, null);
                        final BigDecimal diff = "Debit".equals(postfix) ? sumCredit.subtract(sumDebit)
                                : sumDebit.subtract(sumCredit);

                        final String currAmountStr = _parameter.getParameterValues("amount_" + postfix)[i];
                        final BigDecimal currAmount = StringUtils.isEmpty(currAmountStr) ? BigDecimal.ZERO
                                : (BigDecimal) formater.parse(currAmountStr);

                        final RateInfo rateInfo = getRateInfo4UI(_parameterClone, "_" + postfix, i);

                        final BigDecimal currAmountRate = Currency.convertToCurrency(_parameter, currAmount,
                                rateInfo, null, periodCurrenycInstance).setScale(2, RoundingMode.HALF_UP);

                        final BigDecimal targetRate = currAmountRate.add(diff);

                        if (BigDecimal.ZERO.compareTo(targetRate) < 0) {
                            final RateInfo revRateInfo = rateInfo.reverse();
                            final BigDecimal target = Currency.convertToCurrency(_parameter, targetRate,
                                    revRateInfo, null, rateInfo.getCurrencyInstance())
                                    .setScale(2, RoundingMode.HALF_UP);

                            final String amountStr = formater.format(target);
                            final String amountRateStr = formater.format(targetRate);

                            ret.append(getSetFieldValue(i, "amount_" + postfix, amountStr))
                                    .append(getSetFieldValue(i, "amountRate_" + postfix, amountRateStr));
                            ParameterUtil.setParameterValue(_parameterClone, "amount_" + postfix, i, amountStr);
                            ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + postfix, i,
                                    amountRateStr);

                            final BigDecimal sumDebit2 = getSum4UI(_parameterClone, "Debit", null, null);
                            final BigDecimal sumCredit2 = getSum4UI(_parameterClone, "Credit", null, null);

                            final String sumDebitStr = formater.format(sumDebit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumCreditStr = formater.format(sumCredit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumTotalStr = formater.format(sumDebit2.subtract(sumCredit2).abs())
                                    + " " + new Period().getCurrency(periodInst).getSymbol();

                            ret.append(getSetFieldValue(0, "sumDebit", sumDebitStr))
                                    .append(getSetFieldValue(0, "sumCredit", sumCreditStr))
                                    .append(getSetFieldValue(0, "sumTotal", sumTotalStr));
                            break;
                        }
                    }
                }
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

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

/**
 * Gets the JS 4 fit exchange rate.//from   w w w  .ja  v  a  2 s  .  c  o  m
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _parameterClone the parameter clone
 * @return the JS 4 fit ex rate
 * @throws EFapsException on error
 */
protected StringBuilder getJS4FitExRate(final Parameter _parameter, final Parameter _parameterClone)
        throws EFapsException {
    final StringBuilder ret = new StringBuilder();
    try {
        String postfix = null;
        boolean eval = true;
        while (eval) {
            eval = postfix == null;
            postfix = postfix == null ? "Debit" : "Credit";
            final String[] selected = _parameter.getParameterValues("posSelect_" + postfix);
            if (ArrayUtils.isNotEmpty(selected)) {
                for (int i = 0; i < selected.length; i++) {
                    if (BooleanUtils.toBoolean(selected[i])) {
                        eval = false;
                        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();

                        final Instance periodInst = new Period().evaluateCurrentPeriod(_parameterClone);
                        final Instance periodCurrenycInstance = new Period().getCurrency(periodInst)
                                .getInstance();

                        final BigDecimal sumDebit = getSum4UI(_parameter, "Debit", null, null);
                        final BigDecimal sumCredit = getSum4UI(_parameter, "Credit", null, null);
                        final BigDecimal diff = "Debit".equals(postfix) ? sumCredit.subtract(sumDebit)
                                : sumDebit.subtract(sumCredit);

                        final String currAmountStr = _parameter.getParameterValues("amount_" + postfix)[i];
                        final BigDecimal currAmount = StringUtils.isEmpty(currAmountStr) ? BigDecimal.ZERO
                                : (BigDecimal) formater.parse(currAmountStr);

                        final RateInfo rateInfo = getRateInfo4UI(_parameterClone, "_" + postfix, i);

                        final BigDecimal currAmountRate = Currency.convertToCurrency(_parameter, currAmount,
                                rateInfo, null, periodCurrenycInstance).setScale(2, RoundingMode.HALF_UP);

                        final BigDecimal targetRate = currAmountRate.add(diff);

                        if (BigDecimal.ZERO.compareTo(targetRate) < 0
                                && BigDecimal.ZERO.compareTo(currAmount) < 0) {
                            final BigDecimal rate;
                            if (rateInfo.isInvert()) {
                                rate = targetRate.setScale(8, RoundingMode.HALF_UP).divide(currAmount,
                                        RoundingMode.HALF_UP);
                            } else {
                                rate = currAmount.setScale(8, RoundingMode.HALF_UP).divide(targetRate,
                                        RoundingMode.HALF_UP);
                            }

                            final String rateStr = NumberFormatter.get().getFormatter(null, 8).format(rate);
                            final String amountRateStr = formater.format(targetRate);

                            ret.append(getSetFieldValue(i, "amountRate_" + postfix, amountRateStr))
                                    .append(getSetFieldValue(i, "rate_" + postfix, rateStr));
                            ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + postfix, i,
                                    amountRateStr);
                            ParameterUtil.setParameterValue(_parameterClone, "rate_" + postfix, i, rateStr);

                            final BigDecimal sumDebit2 = getSum4UI(_parameterClone, "Debit", null, null);
                            final BigDecimal sumCredit2 = getSum4UI(_parameterClone, "Credit", null, null);

                            final String sumDebitStr = formater.format(sumDebit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumCreditStr = formater.format(sumCredit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumTotalStr = formater.format(sumDebit2.subtract(sumCredit2).abs())
                                    + " " + new Period().getCurrency(periodInst).getSymbol();

                            ret.append(getSetFieldValue(0, "sumDebit", sumDebitStr))
                                    .append(getSetFieldValue(0, "sumCredit", sumCreditStr))
                                    .append(getSetFieldValue(0, "sumTotal", sumTotalStr));
                            break;
                        }
                    }
                }
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static Object str2num(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    double dRC = 0.00;
    switch (ArgList.length) {
    case 0://  ww w .  ja  va  2s .  c o m
        throw new RuntimeException("The function call str2num requires at least 1 argument.");
    case 1:
        try {
            if (isNull(ArgList[0]))
                return new Double(Double.NaN);
            else if (isUndefined(ArgList[0]))
                return undefinedValue;
            if (ArgList[0].equals(null))
                return null;
            String sArg1 = (String) ArgList[0];
            DecimalFormat formatter = new DecimalFormat();
            dRC = (formatter.parse(Const.ltrim(sArg1))).doubleValue();
        } catch (Exception e) {
            throw new RuntimeException("Could not convert the given String : " + e.getMessage());
        }
        break;
    case 2:
        try {
            if (isNull(ArgList, new int[] { 0, 1 }))
                return new Double(Double.NaN);
            else if (isUndefined(ArgList, new int[] { 0, 1 }))
                return undefinedValue;
            String sArg1 = (String) ArgList[0];
            String sArg2 = (String) ArgList[1];
            if (sArg1.equals("null") || sArg2.equals("null"))
                return null;
            DecimalFormat formatter = new DecimalFormat(sArg2);
            dRC = (formatter.parse(sArg1)).doubleValue();
            return new Double(dRC);
        } catch (Exception e) {
            throw new RuntimeException("Could not convert the String with the given format :" + e.getMessage());
        }
        //break;
    case 3:
        try {
            if (isNull(ArgList, new int[] { 0, 1, 2 }))
                return new Double(Double.NaN);
            else if (isUndefined(ArgList, new int[] { 0, 1, 2 }))
                return undefinedValue;
            String sArg1 = (String) ArgList[0];
            String sArg2 = (String) ArgList[1];
            String sArg3 = (String) ArgList[2];
            if (sArg3.length() == 2) {
                DecimalFormatSymbols dfs = new DecimalFormatSymbols(new Locale(sArg3.toLowerCase()));
                DecimalFormat formatter = new DecimalFormat(sArg2, dfs);
                dRC = (formatter.parse(sArg1)).doubleValue();
                return new Double(dRC);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        break;
    default:
        throw new RuntimeException("The function call str2num requires 1, 2, or 3 arguments.");
    }
    return new Double(dRC);
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static Object str2num(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    double dRC = 0.00;
    switch (ArgList.length) {
    case 0:/*ww  w.j a v a  2 s.co  m*/
        throw Context.reportRuntimeError("The function call str2num requires at least 1 argument.");
    case 1:
        try {
            if (isNull(ArgList[0]))
                return new Double(Double.NaN);
            else if (isUndefined(ArgList[0]))
                return Context.getUndefinedValue();
            if (ArgList[0].equals(null))
                return null;
            String sArg1 = Context.toString(ArgList[0]);
            DecimalFormat formatter = new DecimalFormat();
            dRC = (formatter.parse(Const.ltrim(sArg1))).doubleValue();
        } catch (Exception e) {
            throw Context.reportRuntimeError("Could not convert the given String : " + e.getMessage());
        }
        break;
    case 2:
        try {
            if (isNull(ArgList, new int[] { 0, 1 }))
                return new Double(Double.NaN);
            else if (isUndefined(ArgList, new int[] { 0, 1 }))
                return Context.getUndefinedValue();
            String sArg1 = Context.toString(ArgList[0]);
            String sArg2 = Context.toString(ArgList[1]);
            if (sArg1.equals("null") || sArg2.equals("null"))
                return null;
            DecimalFormat formatter = new DecimalFormat(sArg2);
            dRC = (formatter.parse(sArg1)).doubleValue();
            return new Double(dRC);
        } catch (Exception e) {
            throw Context.reportRuntimeError(
                    "Could not convert the String with the given format :" + e.getMessage());
        }
        //break;
    case 3:
        try {
            if (isNull(ArgList, new int[] { 0, 1, 2 }))
                return new Double(Double.NaN);
            else if (isUndefined(ArgList, new int[] { 0, 1, 2 }))
                return Context.getUndefinedValue();
            String sArg1 = Context.toString(ArgList[0]);
            String sArg2 = Context.toString(ArgList[1]);
            String sArg3 = Context.toString(ArgList[2]);
            if (sArg3.length() == 2) {
                DecimalFormatSymbols dfs = new DecimalFormatSymbols(new Locale(sArg3.toLowerCase()));
                DecimalFormat formatter = new DecimalFormat(sArg2, dfs);
                dRC = (formatter.parse(sArg1)).doubleValue();
                return new Double(dRC);
            }
        } catch (Exception e) {
            throw Context.reportRuntimeError(e.getMessage());
        }
        break;
    default:
        throw Context.reportRuntimeError("The function call str2num requires 1, 2, or 3 arguments.");
    }
    return new Double(dRC);
}

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

/**
 * Calculate the sum for one of the tables.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @param _postFix postfix for the field names
 * @param _pos position/* ww  w.ja va2  s .  com*/
 * @param _rateInfo the _rate info
 * @return sum for the table
 * @throws EFapsException on error
 */
protected BigDecimal getSum4UI(final Parameter _parameter, final String _postFix, final Integer _pos,
        final RateInfo _rateInfo) throws EFapsException {
    final Instance periodInst = new Period().evaluateCurrentPeriod(_parameter);
    final Instance periodCurrenycInstance = new Period().getCurrency(periodInst).getInstance();
    BigDecimal ret = BigDecimal.ZERO;
    try {
        final DecimalFormat formater = NumberFormatter.get().getFormatter(null, null);
        final String[] amounts = _parameter.getParameterValues("amount_" + _postFix);
        if (amounts != null) {
            for (int i = 0; i < amounts.length; i++) {
                final RateInfo rateInfo = _pos != null && i == _pos && _rateInfo != null ? _rateInfo
                        : getRateInfo4UI(_parameter, "_" + _postFix, i);
                final BigDecimal rateAmount = amounts[i] != null && !amounts[i].isEmpty()
                        ? ((BigDecimal) formater.parse(amounts[i])).setScale(8, RoundingMode.HALF_UP)
                        : BigDecimal.ZERO;
                final BigDecimal amount = Currency
                        .convertToCurrency(_parameter, rateAmount, rateInfo, null, periodCurrenycInstance)
                        .setScale(2, RoundingMode.HALF_UP);
                ret = ret.add(amount);
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "getSum.ParseException", e);
    }
    return ret;
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static Object str2num(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    double dRC = 0.00;
    switch (ArgList.length) {
    case 0://from   w w w .  ja  v a2 s.c o  m
        throw new RuntimeException("The function call str2num requires at least 1 argument.");
    case 1:
        try {
            if (isNull(ArgList[0])) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList[0])) {
                return undefinedValue;
            }
            if (ArgList[0].equals(null)) {
                return null;
            }
            String sArg1 = (String) ArgList[0];
            DecimalFormat formatter = new DecimalFormat();
            dRC = (formatter.parse(Const.ltrim(sArg1))).doubleValue();
        } catch (Exception e) {
            throw new RuntimeException("Could not convert the given String : " + e.getMessage());
        }
        break;
    case 2:
        try {
            if (isNull(ArgList, new int[] { 0, 1 })) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList, new int[] { 0, 1 })) {
                return undefinedValue;
            }
            String sArg1 = (String) ArgList[0];
            String sArg2 = (String) ArgList[1];
            if (sArg1.equals("null") || sArg2.equals("null")) {
                return null;
            }
            DecimalFormat formatter = new DecimalFormat(sArg2);
            dRC = (formatter.parse(sArg1)).doubleValue();
            return new Double(dRC);
        } catch (Exception e) {
            throw new RuntimeException("Could not convert the String with the given format :" + e.getMessage());
        }
        // break;
    case 3:
        try {
            if (isNull(ArgList, new int[] { 0, 1, 2 })) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList, new int[] { 0, 1, 2 })) {
                return undefinedValue;
            }
            String sArg1 = (String) ArgList[0];
            String sArg2 = (String) ArgList[1];
            String sArg3 = (String) ArgList[2];
            if (sArg3.length() == 2) {
                DecimalFormatSymbols dfs = new DecimalFormatSymbols(EnvUtil.createLocale(sArg3.toLowerCase()));
                DecimalFormat formatter = new DecimalFormat(sArg2, dfs);
                dRC = (formatter.parse(sArg1)).doubleValue();
                return new Double(dRC);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        break;
    default:
        throw new RuntimeException("The function call str2num requires 1, 2, or 3 arguments.");
    }
    return new Double(dRC);
}

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

/**
 * Used form a from to create the transaction for opening a balance.
 *
 * @param _parameter Paramter as passed from the eFaps API
 * @return new Return//w  w  w  .j  a va 2 s  .  co m
 * @throws EFapsException on error
 */
public Return createTransactionOpeningBalance(final Parameter _parameter) throws EFapsException {
    final String debitAccOId = _parameter.getParameterValue("accountLink_Debit");
    final String[] amounts = _parameter.getParameterValues("amount");
    final String[] accounts = _parameter.getParameterValues("accountLink_Credit");
    final Instance periodInst = _parameter.getInstance();

    final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance);
    insert.add(CIAccounting.TransactionOpeningBalance.Name, 0);
    insert.add(CIAccounting.TransactionOpeningBalance.Description,
            DBProperties.getProperty("org.efaps.esjp.accounting.Transaction.openingBalance.description"));
    insert.add(CIAccounting.TransactionOpeningBalance.Date, _parameter.getParameterValue("date"));
    insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst.getId());
    insert.add(CIAccounting.TransactionOpeningBalance.Status,
            ((Long) Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId()).toString());
    insert.execute();

    BigDecimal debitAmount = BigDecimal.ZERO;
    final CurrencyInst curr = new Period().getCurrency(periodInst);
    final DecimalFormat formater = NumberFormatter.get().getFormatter(null, 2);
    for (int i = 0; i < amounts.length; i++) {
        final Instance accInst = Instance.get(accounts[i]);
        final PrintQuery print = new PrintQuery(accInst);
        print.addAttribute(CIAccounting.AccountAbstract.SumReport);
        print.execute();

        final BigDecimal sumreport = print.<BigDecimal>getAttribute(CIAccounting.AccountAbstract.SumReport);
        try {
            BigDecimal amount = (BigDecimal) formater.parse(amounts[i]);
            amount = amount.subtract(sumreport == null ? BigDecimal.ZERO : sumreport);
            final CIType type = amount.compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit
                    : CIAccounting.TransactionPositionDebit;
            final Insert posInsert = new Insert(type);
            posInsert.add(CIAccounting.TransactionPositionAbstract.AccountLink, accInst.getId());
            posInsert.add(CIAccounting.TransactionPositionAbstract.Amount, amount);
            posInsert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curr.getInstance().getId());
            posInsert.add(CIAccounting.TransactionPositionAbstract.Rate, new Object[] { 1, 1 });
            posInsert.add(CIAccounting.TransactionPositionAbstract.RateAmount, amount);
            posInsert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink,
                    curr.getInstance().getId());
            posInsert.add(CIAccounting.TransactionPositionAbstract.TransactionLink,
                    insert.getInstance().getId());
            posInsert.execute();
            debitAmount = debitAmount.add(amount);
        } catch (final ParseException e) {
            throw new EFapsException(Create_Base.class, "createTransactionOpeningBalance", e);
        }
    }
    final Instance accInst = Instance.get(debitAccOId);
    final CIType type = debitAmount.compareTo(BigDecimal.ZERO) < 0 ? CIAccounting.TransactionPositionCredit
            : CIAccounting.TransactionPositionDebit;
    final Insert posInsert = new Insert(type);
    posInsert.add(CIAccounting.TransactionPositionAbstract.AccountLink, accInst.getId());
    posInsert.add(CIAccounting.TransactionPositionAbstract.Amount, debitAmount.negate());
    posInsert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curr.getInstance().getId());
    posInsert.add(CIAccounting.TransactionPositionAbstract.Rate, new Object[] { 1, 1 });
    posInsert.add(CIAccounting.TransactionPositionAbstract.RateAmount, debitAmount.negate());
    posInsert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, curr.getInstance().getId());
    posInsert.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance().getId());
    posInsert.execute();

    return new Return();
}

From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static Object str2num(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    double dRC = 0.00;
    switch (ArgList.length) {
    case 0://from w w w.  j  a v a  2  s .c  om
        throw Context.reportRuntimeError("The function call str2num requires at least 1 argument.");
    case 1:
        try {
            if (isNull(ArgList[0])) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList[0])) {
                return Context.getUndefinedValue();
            }
            if (ArgList[0].equals(null)) {
                return null;
            }
            String sArg1 = Context.toString(ArgList[0]);
            DecimalFormat formatter = new DecimalFormat();
            dRC = (formatter.parse(Const.ltrim(sArg1))).doubleValue();
        } catch (Exception e) {
            throw Context.reportRuntimeError("Could not convert the given String : " + e.getMessage());
        }
        break;
    case 2:
        try {
            if (isNull(ArgList, new int[] { 0, 1 })) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList, new int[] { 0, 1 })) {
                return Context.getUndefinedValue();
            }
            String sArg1 = Context.toString(ArgList[0]);
            String sArg2 = Context.toString(ArgList[1]);
            if (sArg1.equals("null") || sArg2.equals("null")) {
                return null;
            }
            DecimalFormat formatter = new DecimalFormat(sArg2);
            dRC = (formatter.parse(sArg1)).doubleValue();
            return new Double(dRC);
        } catch (Exception e) {
            throw Context.reportRuntimeError(
                    "Could not convert the String with the given format :" + e.getMessage());
        }
        // break;
    case 3:
        try {
            if (isNull(ArgList, new int[] { 0, 1, 2 })) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList, new int[] { 0, 1, 2 })) {
                return Context.getUndefinedValue();
            }
            String sArg1 = Context.toString(ArgList[0]);
            String sArg2 = Context.toString(ArgList[1]);
            String sArg3 = Context.toString(ArgList[2]);
            if (sArg3.length() == 2) {
                DecimalFormatSymbols dfs = new DecimalFormatSymbols(EnvUtil.createLocale(sArg3.toLowerCase()));
                DecimalFormat formatter = new DecimalFormat(sArg2, dfs);
                dRC = (formatter.parse(sArg1)).doubleValue();
                return new Double(dRC);
            }
        } catch (Exception e) {
            throw Context.reportRuntimeError(e.getMessage());
        }
        break;
    default:
        throw Context.reportRuntimeError("The function call str2num requires 1, 2, or 3 arguments.");
    }
    return new Double(dRC);
}

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

/**
 * Analyse positions from ui./*  w  w w  . j  a  v  a 2 s .  c om*/
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _transInfo the trans info
 * @param _postFix the post fix
 * @param _accountOids the account oids
 * @param _executeRels the execute rels
 * @throws EFapsException on error
 */
public void analysePositionsFromUI(final Parameter _parameter, final TransInfo _transInfo,
        final String _postFix, final String[] _accountOids, final boolean _executeRels) throws EFapsException {
    @SuppressWarnings("unchecked")
    final Map<String, String> oidMap = (Map<String, String>) _parameter.get(ParameterValues.OIDMAP4UI);

    final String[] rowKeys = InterfaceUtils.getRowKeys(_parameter, "amount_" + _postFix, "amount_Debit",
            "amount_Credit");

    final String[] accountOids = _accountOids == null ? _parameter.getParameterValues("accountLink_" + _postFix)
            : _accountOids;
    final String[] amounts = _parameter.getParameterValues("amount_" + _postFix);
    final String[] types = _parameter.getParameterValues("type_" + _postFix);
    final String[] rateCurIds = _parameter.getParameterValues("rateCurrencyLink_" + _postFix);
    final String[] acc2accOids = _parameter.getParameterValues("acc2acc_" + _postFix);
    final String[] labelLinkOids = _parameter.getParameterValues("labelLink_" + _postFix);
    final String[] docLinkOids = _parameter.getParameterValues("docLink_" + _postFix);
    final String[] remarks = _parameter.getParameterValues("remark_" + _postFix);
    final DecimalFormat formater = NumberFormatter.get().getFormatter();
    try {
        Instance inst = _parameter.getCallInstance();
        if (!inst.getType().isKindOf(CIAccounting.Period.getType())) {
            inst = new Period().evaluateCurrentPeriod(_parameter);
        }
        final Instance curInstance = new Period().getCurrency(inst).getInstance();
        if (amounts != null) {
            for (int i = 0; i < amounts.length; i++) {
                final Instance rateCurrInst = CurrencyInst.get(Long.parseLong(rateCurIds[i])).getInstance();
                final Instance accInst = Instance.get(accountOids[i]);
                final Object[] rateObj = getRateObject(_parameter, "_" + _postFix, i);
                final RateInfo rateInfo = getRateInfo4UI(_parameter, "_" + _postFix, i);

                final Type type = Type.get(Long.parseLong(types[i]));
                final boolean isDebitTrans = type.getUUID().equals(CIAccounting.TransactionPositionDebit.uuid);

                final BigDecimal rateAmount = ((BigDecimal) formater.parse(amounts[i])).setScale(2,
                        RoundingMode.HALF_UP);
                final BigDecimal amount = Currency
                        .convertToCurrency(_parameter, rateAmount, rateInfo, null, curInstance)
                        .setScale(2, RoundingMode.HALF_UP);

                final PositionInfo pos = new PositionInfo();
                _transInfo.addPosition(pos);
                pos.setType(type).setAccInst(accInst).setCurrInst(curInstance).setRateCurrInst(rateCurrInst)
                        .setRate(rateObj).setRateAmount(isDebitTrans ? rateAmount.negate() : rateAmount)
                        .setAmount(isDebitTrans ? amount.negate() : amount).setOrder(i)
                        .setRemark(remarks == null ? null : remarks[i])
                        .setInstance(Instance.get(oidMap.get(rowKeys[i])));

                if (labelLinkOids != null) {
                    final Instance labelInst = Instance.get(labelLinkOids[i]);
                    if (labelInst.isValid()) {
                        pos.setLabelInst(labelInst)
                                .setLabelRelType(_postFix.equalsIgnoreCase("Debit")
                                        ? CIAccounting.TransactionPositionDebit2LabelProject.getType()
                                        : CIAccounting.TransactionPositionCredit2LabelProject.getType());
                    }
                }

                if (docLinkOids != null) {
                    final Instance docInst = Instance.get(docLinkOids[i]);
                    if (docInst.isValid()) {
                        final DocumentInfo docInfoTmp = new DocumentInfo(docInst);
                        if (docInfoTmp.isSumsDoc()) {
                            pos.setDocInst(docInst)
                                    .setDocRelType(_postFix.equalsIgnoreCase("Debit")
                                            ? CIAccounting.TransactionPositionDebit2SalesDocument.getType()
                                            : CIAccounting.TransactionPositionCredit2SalesDocument.getType());
                        } else {
                            pos.setDocInst(docInst)
                                    .setDocRelType(_postFix.equalsIgnoreCase("Debit")
                                            ? CIAccounting.TransactionPositionDebit2PaymentDocument.getType()
                                            : CIAccounting.TransactionPositionCredit2PaymentDocument.getType());
                        }
                    }
                }
                if (_executeRels) {
                    final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.Account2AccountAbstract);
                    queryBldr.addWhereAttrEqValue(CIAccounting.Account2AccountAbstract.FromAccountLink,
                            accInst);
                    final MultiPrintQuery multi = queryBldr.getPrint();
                    final SelectBuilder selAcc = SelectBuilder.get()
                            .linkto(CIAccounting.Account2AccountAbstract.ToAccountLink).instance();
                    multi.addSelect(selAcc);
                    multi.addAttribute(CIAccounting.Account2AccountAbstract.Numerator,
                            CIAccounting.Account2AccountAbstract.Denominator,
                            CIAccounting.Account2AccountAbstract.Config);
                    multi.execute();
                    int y = 1;
                    final int group = _transInfo.getNextGroup();
                    while (multi.next()) {
                        final Instance instance = multi.getCurrentInstance();
                        final PositionInfo connPos = new PositionInfo();
                        connPos.setPosType(TransPosType.CONNECTION);
                        final Collection<Accounting.Account2AccountConfig> configs = multi
                                .getAttribute(CIAccounting.Account2AccountAbstract.Config);
                        final boolean deactivatable = configs != null
                                && configs.contains(Accounting.Account2AccountConfig.DEACTIVATABLE);
                        final boolean confCheck = isDebitTrans && configs != null
                                && configs.contains(Accounting.Account2AccountConfig.APPLY4DEBIT)
                                || !isDebitTrans && configs != null
                                        && configs.contains(Accounting.Account2AccountConfig.APPLY4CREDIT);

                        // if cannot be deactivated or selected in the UserInterface
                        if (confCheck && (!deactivatable || acc2accOids != null && deactivatable
                                && Arrays.asList(acc2accOids).contains(instance.getOid()))) {
                            final BigDecimal numerator = new BigDecimal(multi
                                    .<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Numerator));
                            final BigDecimal denominator = new BigDecimal(multi
                                    .<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Denominator));

                            BigDecimal amount2 = amount.multiply(numerator).divide(denominator,
                                    BigDecimal.ROUND_HALF_UP);
                            BigDecimal rateAmount2 = rateAmount.multiply(numerator).divide(denominator,
                                    BigDecimal.ROUND_HALF_UP);

                            if (instance.getType().isCIType(CIAccounting.Account2AccountCosting)) {
                                connPos.setType(type);
                            } else if (instance.getType()
                                    .isCIType(CIAccounting.Account2AccountCostingInverse)) {
                                if (type.getUUID().equals(CIAccounting.TransactionPositionDebit.uuid)) {
                                    connPos.setType(CIAccounting.TransactionPositionCredit.getType());
                                } else {
                                    connPos.setType(CIAccounting.TransactionPositionDebit.getType());
                                }
                                amount2 = amount2.negate();
                            } else if (instance.getType().isCIType(CIAccounting.Account2AccountCredit)) {
                                if (isDebitTrans) {
                                    connPos.setType(CIAccounting.TransactionPositionCredit.getType());
                                } else {
                                    connPos.setType(CIAccounting.TransactionPositionDebit.getType());
                                    amount2 = amount2.negate();
                                    rateAmount2 = rateAmount2.negate();
                                }
                            } else if (instance.getType().isCIType(CIAccounting.Account2AccountDebit)) {
                                if (isDebitTrans) {
                                    connPos.setType(CIAccounting.TransactionPositionDebit.getType());
                                    amount2 = amount2.negate();
                                    rateAmount2 = rateAmount2.negate();
                                } else {
                                    connPos.setType(CIAccounting.TransactionPositionCredit.getType());
                                }
                            }
                            if (connPos.getType() == null) {
                                Create_Base.LOG.error("Missing definition");
                            } else {
                                connPos.setOrder(i).setConnOrder(y).setGroupId(group)
                                        .setAccInst(multi.<Instance>getSelect(selAcc)).setCurrInst(curInstance)
                                        .setRateCurrInst(rateCurrInst).setRate(rateObj).setAmount(amount2)
                                        .setRateAmount(rateAmount2);
                                _transInfo.addPosition(connPos);
                            }
                            y++;
                        }
                    }
                }
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "insertPositions", e);
    }
}