Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

In this page you can find the example usage for java.math BigDecimal subtract.

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

Returns a BigDecimal whose value is (this - subtrahend) , and whose scale is max(this.scale(), subtrahend.scale()) .

Usage

From source file:uk.ac.leeds.ccg.andyt.projects.moses.process.Comparison.java

public void compareCASUV003WithCAS001() throws Exception {
    File infile;// w ww.  j a  va2s  .c o m
    infile = new File("C:/Work/Projects/MoSeS/Workspace/UV003.dat");
    CASUV003DataHandler cASUV003DataHandler = new CASUV003DataHandler(infile);
    infile = new File("C:/Work/Projects/MoSeS/Workspace/CAS001.dat");
    CAS001DataHandler tCAS001DataHandler = new CAS001DataHandler(infile);

    CASUV003DataRecord aCASUV003DataRecord;
    CAS001DataRecord aCAS001DataRecord;
    long difference;
    long maxDifference = Long.MIN_VALUE;
    long sumOfSquaredDifference = 0L;
    long totalDifference = 0L;
    long absoluteDifference = 0L;
    long totalAbsoluteDifference = 0L;
    long RecordID;
    long nRecords = cASUV003DataHandler.getNDataRecords();
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        difference = (long) (aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        if (difference < 0) {
            absoluteDifference = difference * -1L;
        }
        sumOfSquaredDifference += (difference * difference);
        maxDifference = Math.max(maxDifference, difference);
        totalDifference += difference;
        totalAbsoluteDifference += absoluteDifference;
    }
    int scale = 100;
    int roundingMode = BigDecimal.ROUND_HALF_EVEN;
    BigDecimal nRecordsBigDecimal = new BigDecimal(nRecords);
    BigDecimal meanDifferenceBigDecimal = new BigDecimal(maxDifference).divide(nRecordsBigDecimal, scale,
            roundingMode);
    System.out.println("nRecords " + nRecords);
    System.out.println("meanDifferenceBigDecimal " + meanDifferenceBigDecimal.toString());
    System.out.println("sumOfSquaredDifference " + sumOfSquaredDifference);
    System.out.println("maxDifference " + maxDifference);
    System.out.println("totalAbsoluteDifference " + totalAbsoluteDifference);
    System.out.println("totalDifference " + totalDifference);
    BigDecimal standardDeviationOfDifferenceBigDecimal = new BigDecimal("0");
    BigDecimal differenceBigDecimal;
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        differenceBigDecimal = new BigDecimal(
                aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        standardDeviationOfDifferenceBigDecimal = differenceBigDecimal.multiply(differenceBigDecimal);
    }
    standardDeviationOfDifferenceBigDecimal = standardDeviationOfDifferenceBigDecimal
            .divide(nRecordsBigDecimal.subtract(BigDecimal.ONE), scale, roundingMode);
    standardDeviationOfDifferenceBigDecimal = Generic_BigDecimal.sqrt(standardDeviationOfDifferenceBigDecimal,
            scale, RoundingMode.HALF_EVEN);
    System.out.println("standardDeviationOfDifferenceBigDecimal " + standardDeviationOfDifferenceBigDecimal);
}

From source file:org.kuali.ole.module.purap.document.web.struts.OleRequisitionAction.java

/**
 * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
 *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from w  ww .  jav  a2  s .  co  m
@Override
public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
    PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;

    // index of item selected
    int itemIndex = getSelectedLine(request);
    PurApItem item = null;

    // if custom processing of an accounting line is not done then insert a line generically.
    if (processCustomInsertAccountingLine(purapForm, request) == false) {
        String errorPrefix = null;
        PurApAccountingLine line = null;

        boolean rulePassed = false;
        if (itemIndex >= 0) {
            item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
            // calculating the dollar amount for the accounting Line.
            PurApAccountingLine lineItem = item.getNewSourceLine();
            if (item.getTotalAmount() != null && !item.getTotalAmount().equals(KualiDecimal.ZERO)) {
                if (lineItem.getAccountLinePercent() != null
                        && (lineItem.getAmount() == null || lineItem.getAmount().equals(KualiDecimal.ZERO))) {
                    BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
                    lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
                } else if (lineItem.getAmount() != null && lineItem.getAmount().isNonZero()
                        && lineItem.getAccountLinePercent() == null) {
                    KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
                    BigDecimal dollarToPercent = dollar.bigDecimalValue()
                            .divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
                    lineItem.setAccountLinePercent(dollarToPercent);
                } else if (lineItem.getAmount() != null && lineItem.getAmount().isZero()
                        && lineItem.getAccountLinePercent() == null) {
                    lineItem.setAccountLinePercent(new BigDecimal(0));
                } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent().intValue() == 100) {
                    KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
                    BigDecimal dollarToPercent = dollar.bigDecimalValue()
                            .divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
                    lineItem.setAccountLinePercent(dollarToPercent);
                } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() != null) {
                    BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
                    lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
                }
            } else {
                lineItem.setAmount(new KualiDecimal(0));
            }
            line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
            //end
            //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
            errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "["
                    + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
            rulePassed = SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
        } else if (itemIndex == -2) {
            //corrected: itemIndex == -2 is the only case for distribute account
            //This is the case when we're inserting an accounting line for distribute account.
            line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
            //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
            errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
            rulePassed = SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
        }
        if (rulePassed) {
            AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
            if (accountingLineBase != null) {
                String accountNumber = accountingLineBase.getAccountNumber();
                String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
                Map<String, String> criteria = new HashMap<String, String>();
                criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
                criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
                Account account = SpringContext.getBean(BusinessObjectService.class)
                        .findByPrimaryKey(Account.class, criteria);
                rulePassed = checkForValidAccount(account);
            }
        }
        if (rulePassed) {
            // add accountingLine
            SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
            PurApAccountingLine newSourceLine = item.getNewSourceLine();
            List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines();

            BigDecimal initialValue = OleSelectConstant.ZERO_PERCENT;

            for (PurApAccountingLine accountLine : existingSourceLine) {
                initialValue = initialValue.add(accountLine.getAccountLinePercent());

            }
            if (itemIndex >= 0) {

                if ((newSourceLine.getAccountLinePercent()
                        .intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED
                        && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT
                                .subtract(initialValue).intValue())
                        && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) {
                    if (OleSelectConstant.MAX_PERCENT.subtract(initialValue)
                            .intValue() != OleSelectConstant.ZERO) {
                        insertAccountingLine(purapForm, item, line);
                    }
                } else {
                    checkAccountingLinePercent(newSourceLine);

                }
                for (PurApAccountingLine oldSourceAccountingLine : item.getSourceAccountingLines()) {
                    if (oldSourceAccountingLine instanceof OleRequisitionAccount) {
                        ((OleRequisitionAccount) oldSourceAccountingLine)
                                .setExistingAmount(oldSourceAccountingLine.getAmount());
                    }
                }
                List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines();
                BigDecimal totalPercent = new BigDecimal(100);
                BigDecimal initialPercent = new BigDecimal(0);
                for (PurApAccountingLine purApAccountingLine : existingAccountingLine) {
                    initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());

                }
                initialPercent = totalPercent.subtract(initialPercent);
                BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT);
                if (maxPercent.intValue() == OleSelectConstant.ZERO) {
                    item.resetAccount(OleSelectConstant.ZERO_PERCENT);

                } else {
                    item.resetAccount(initialPercent);

                }
            } else if (itemIndex == -2) {
                //this is the case for distribute account
                ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
            }
        }
    }

    return mapping.findForward(OLEConstants.MAPPING_BASIC);
}

From source file:ch.unil.genescore.vegas.FarebrotherExperiment.java

/**
 * ruben.cpp:/*from w  w w  .  ja  v  a  2 s . co m*/
 * Algorithm AS 204 Appl. Statist. (1984) Vol. 33, No.3
 * ruben evaluates the probability that a positive definite quadratic form in Normal variates is less than a given value
 */
private void ruben() {

    ifault_ = -41; // I added this initialization --daniel

    //void ruben(double *lambda, int *mult, double *delta, int *n, double *c, double *mode, int *maxit, double *eps, double *dnsty, int *ifault, double *res) {
    // Initialized at 0 in the R code
    double dnsty = 0.0;

    int i, k, m, j;
    //double pnorm(double q, double mean, double sd, int lower_tail, int log_p);
    double ao, aoinv, z, bbeta, eps2, hold, hold2, sum, sum1, dans, lans, pans, prbty, prbtyAgain, tol;

    double[] gamma = new double[lambda_.length];
    double[] theta = new double[lambda_.length];
    double[] a = new double[maxit_];
    double[] b = new double[maxit_];

    if ((lambda_.length < 1) || (q_ <= 0) || (maxit_ < 1) || (eps_ <= 0.0)) {
        //res_ = -2.0;
        ifault_ = 2;
        return;
    }

    tol = -200.0;

    // Preliminaries
    sum = lambda_[0];
    bbeta = sum;

    for (i = 1; i <= lambda_.length; i++) {
        hold = lambda_[i - 1];
        if ((hold <= 0.0) || (h_[i - 1] < 1) || (delta_[i - 1] < 0.0)) {
            res_ = -7.1;//new BigDecimal(-71.0);

            ifault_ = -i;
            return;
        }
        if (bbeta > hold)
            bbeta = hold; // calcul du max des lambdas
        if (sum < hold)
            sum = hold; // calcul du min des lambdas
    }

    if (mode_ > 0.0) {
        // if ((2.0/(1.0/bbeta+1.0/sum))>1.8*sum) bbeta = sum; // comme dans NAG : methode avec betaA
        bbeta = mode_ * bbeta;
    } else {
        bbeta = 2.0 / (1.0 / bbeta + 1.0 / sum); // methode avec betaB
    }

    k = 0;
    sum = 1.0;
    sum1 = 0.0;
    for (i = 1; i <= lambda_.length; i++) {
        hold = bbeta / lambda_[i - 1];
        gamma[i - 1] = 1.0 - hold;
        sum = sum * Math.pow(hold, h_[i - 1]); //???? pas sur ..
        sum1 = sum1 + delta_[i - 1];
        k = k + h_[i - 1];
        theta[i - 1] = 1.0;
    }

    ao = Math.exp(0.5 * (Math.log(sum) - sum1));
    if (ao <= 0.0) {
        res_ = 0.0;//new BigDecimal(0.0);

        dnsty = 0.0;
        ifault_ = 1; // returns after this (the rest of the function is in the else)
    } else { // evaluate probability and density of chi-squared on k degrees of freedom. The constant 0.22579135264473 is ln(sqrt(pi/2))
        z = q_ / bbeta;

        if ((k % 2) == 0) { // k est un entier donc on regarde si k est divisible par 2: k == (k/2)*k 
            i = 2;
            lans = -0.5 * z;
            dans = Math.exp(lans);
            pans = 1.0 - dans;
        } else {
            i = 1;
            lans = -0.5 * (z + Math.log(z)) - 0.22579135264473;
            dans = Math.exp(lans);
            //pans = pnorm(Math.sqrt(z),0.0,1.0,1,0) - pnorm(-Math.sqrt(z),0.0,1.0,1,0); 
            pans = normal_.cumulativeProbability(Math.sqrt(z)) - normal_.cumulativeProbability(-Math.sqrt(z));
        }

        k = k - 2;
        for (j = i; j <= k; j = j + 2) {
            if (lans < tol) {
                lans = lans + Math.log(z / (double) j);
                dans = Math.exp(lans);
            } else {
                dans = dans * z / (double) j;
            }
            pans = pans - dans;
        }

        // evaluate successive terms of expansion

        prbty = pans;

        prbtyAgain = 1 - ao * pans;
        BigDecimal prbtyBig = new BigDecimal(prbtyAgain);
        dnsty = dans;
        eps2 = eps_ / ao;
        aoinv = 1.0 / ao;
        sum = aoinv - 1.0;

        for (m = 1; m <= maxit_; m++) {
            sum1 = 0.0;
            for (i = 1; i <= lambda_.length; i++) {
                hold = theta[i - 1];
                hold2 = hold * gamma[i - 1];
                theta[i - 1] = hold2;
                sum1 = sum1 + hold2 * h_[i - 1] + m * delta_[i - 1] * (hold - hold2);
            }
            sum1 = 0.5 * sum1;
            b[m - 1] = sum1;
            for (i = m - 1; i >= 1; i--) {
                sum1 = sum1 + b[i - 1] * a[m - i - 1];
            }
            sum1 = sum1 / (double) m;
            a[m - 1] = sum1;
            k = k + 2;
            if (lans < tol) {
                lans = lans + Math.log(z / (double) k);
                dans = Math.exp(lans);
            } else {
                dans = dans * z / (double) k;
            }
            pans = pans - dans;
            sum = sum - sum1;
            dnsty = dnsty + dans * sum1;
            sum1 = pans * sum1;
            prbty = prbty + sum1;
            prbtyBig.subtract(new BigDecimal(sum1));
            prbtyAgain = prbtyAgain - ao * sum1;
            if (prbty < (-aoinv)) {
                res_ = -3.0;//new BigDecimal(-3.0);

                //res_ = -3.0;
                ifault_ = 3;
                return;
            }
            if (Math.abs(pans * sum) < eps2) {
                if (Math.abs(sum1) < eps2) {
                    //if (Math.abs(sum) < eps2) {
                    ifault_ = 0; // this is overwritten below (ifault_=4) -- I now changed the code below
                    // I COMMENTED THIS SO WE CAN See IF THERE WAS CONVERGENCE OR NOT -daniel
                    //m = maxit_+1; // and WHY would you do that?
                    break;
                    //}
                }
            }
        }

        if (m > maxit_) // I ADDED THIS IF, OTHERWISE IT MAKES NO SENSE -daniel
            ifault_ = 4;
        // Check if I understood correctly
        assert ifault_ == 0 || ifault_ == 4;

        dnsty = ao * dnsty / (bbeta + bbeta);
        prbty = ao * prbty;
        //prbtyAgain=ao*prbtyAgain + (1-ao);
        //prbtyBig.multiply(new BigDecimal(ao));

        //prbtyBig.add(new BigDecimal(1.0));
        //prbtyBig.subtract(new BigDecimal(ao));
        //prtbyBig.subtract(ao);
        // With my edits above, this now makes a bit mores sense
        if (prbty < 0.0 || prbty > 1.0) {
            ifault_ = ifault_ + 5; // why the ... would they write it like this? I.e., ifault_ = 9
        } else {
            if (dnsty < 0.0)
                ifault_ = ifault_ + 6;
        }
        res_ = prbtyAgain;
    }

    return;
}

From source file:com.nkapps.billing.dao.OverpaymentDaoImpl.java

private void returnStateRevert(Session session, BankStatement bs, BigDecimal overpaymentSum,
        Long issuerSerialNumber, String issuerIp, LocalDateTime dateTime) throws Exception {
    if (!bs.getBankStatementPayments().isEmpty()) { // if bankstatement has payments
        String q = " SELECT p.id AS id, p.tin AS tin, p.paymentNum AS paymentNum, p.paymentDate AS paymentDate,"
                + "  p.paymentSum AS paymentSum, p.sourceCode AS sourceCode,"
                + " p.state AS state, p.tinDebtor as tinDebtor,p.claim as claim, p.issuerSerialNumber as issuerSerialNumber,"
                + " p.issuerIp as issuerIp,p.dateCreated AS dateCreated, p.dateUpdated as dateUpdated, "
                + " p.paymentSum - COALESCE((SELECT SUM(paidSum) FROM KeyPayment kp WHERE kp.payment = p),0) AS overSum "
                + " FROM Payment p JOIN p.bankStatementPayment bsp " + " WHERE p.claim = 0 "
                + " AND bsp.id.bankStatement = :bs" + " ORDER BY p.paymentDate, p.paymentNum ";
        Query query = session.createQuery(q);
        query.setParameter("bs", bs);
        query.setResultTransformer(Transformers.aliasToBean(Payment.class));
        List<Payment> paymentList = query.list();

        int listSize = paymentList.size();
        int currentIndex = 0;
        BigDecimal keyCost = new BigDecimal(bankStatementDao.getKeyCost());

        for (Payment payment : paymentList) {
            currentIndex++;// ww  w  . java 2 s . c  o m

            overpaymentSum = overpaymentSum.subtract(payment.getOverSum());

            if (currentIndex == listSize) {
                if (payment.getState() == 3) {
                    if (payment.getPaymentSum().compareTo(BigDecimal.ZERO) > 0) {
                        payment.setState((short) 2);
                    } else {
                        payment.setState((short) 1);
                    }
                }
                payment.setPaymentSum(payment.getPaymentSum().add(overpaymentSum));
                payment.setIssuerSerialNumber(issuerSerialNumber);
                payment.setIssuerIp(issuerIp);
                payment.setDateUpdated(dateTime);

                session.update(payment);

                overpaymentSum = BigDecimal.ZERO;

            } else {
                if (payment.getPaymentSum().compareTo(keyCost) < 0) {

                    BigDecimal paymentSum = payment.getPaymentSum();

                    if (overpaymentSum.add(paymentSum).compareTo(keyCost) <= 0) {
                        if (payment.getState() == 3) {
                            if (payment.getPaymentSum().compareTo(BigDecimal.ZERO) > 0) {
                                payment.setState((short) 2);
                            } else {
                                payment.setState((short) 1);
                            }
                        }
                        payment.setPaymentSum(overpaymentSum.add(paymentSum));
                        payment.setIssuerSerialNumber(issuerSerialNumber);
                        payment.setIssuerIp(issuerIp);
                        payment.setDateUpdated(dateTime);

                        session.update(payment);

                        overpaymentSum = BigDecimal.ZERO;
                    } else {
                        if (payment.getState() == 3) {
                            if (payment.getPaymentSum().compareTo(BigDecimal.ZERO) > 0) {
                                payment.setState((short) 2);
                            } else {
                                payment.setState((short) 1);
                            }
                        }
                        payment.setPaymentSum(keyCost);
                        payment.setIssuerSerialNumber(issuerSerialNumber);
                        payment.setIssuerIp(issuerIp);
                        payment.setDateUpdated(dateTime);

                        session.update(payment);

                        overpaymentSum = overpaymentSum.add(paymentSum).subtract(keyCost);
                    }
                }
            }

            if (overpaymentSum.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
        }
    }
}

From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java

private BigDecimal createLineForTaxUndeductable(int invoiceLineTaxCount, int totalInvoiceLineTax,
        BigDecimal cumulativeTaxLineAmount, BigDecimal taxAmount, DocInvoiceData[] data,
        ConnectionProvider conn, Fact fact, DocLine docLine, String Fact_Acct_Group_ID) {
    for (int j = 0; j < data.length; j++) {
        invoiceLineTaxCount++;//ww w.  j a v  a 2  s. c  om
        // We have to adjust the amount in last line of tax
        if (invoiceLineTaxCount == totalInvoiceLineTax) {
            data[j].taxamt = taxAmount.subtract(cumulativeTaxLineAmount).toPlainString();
        }
        try {
            // currently applicable for API and APC
            if (this.DocumentType.equals(AcctServer.DOCTYPE_APInvoice)) {
                if (IsReversal.equals("Y")) {
                    fact.createLine(docLine, Account.getAccount(conn, data[j].pExpenseAcct), this.C_Currency_ID,
                            "", data[j].taxamt, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);

                } else {
                    fact.createLine(docLine, Account.getAccount(conn, data[j].pExpenseAcct), this.C_Currency_ID,
                            data[j].taxamt, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
                }
            } else if (this.DocumentType.equals(AcctServer.DOCTYPE_APCredit)) {
                fact.createLine(docLine, Account.getAccount(conn, data[j].pExpenseAcct), this.C_Currency_ID, "",
                        data[j].taxamt, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
            }
            cumulativeTaxLineAmount = cumulativeTaxLineAmount.add(new BigDecimal(data[j].taxamt));
        } catch (ServletException e) {
            log4jDocInvoice.error("Exception in createLineForTaxUndeductable method: " + e);
        }

    }

    return cumulativeTaxLineAmount;
}

From source file:org.egov.ptis.actions.common.AjaxCommonAction.java

/**
 * API to calculate Mutation Fee dynamically
 *
 * @return/*from w  w w. j  a  va 2  s.c o  m*/
 */
@Action(value = "/ajaxCommon-calculateMutationFee")
public String calculateMutationFee() {
    // Maximum among partyValue and departmentValue will be considered as
    // the documentValue
    final BigDecimal documentValue = partyValue.compareTo(departmentValue) > 0 ? partyValue : departmentValue;

    if (documentValue.compareTo(ZERO) > 0) {
        BigDecimal excessDocValue;
        BigDecimal multiplicationFactor;
        final MutationFeeDetails mutationFeeDetails = (MutationFeeDetails) getPersistenceService().find(
                "from MutationFeeDetails where lowLimit <= ? and (highLimit is null OR highLimit >= ?) and toDate > now()",
                documentValue, documentValue);
        if (mutationFeeDetails != null) {
            if (mutationFeeDetails.getFlatAmount() != null
                    && mutationFeeDetails.getFlatAmount().compareTo(ZERO) > 0)
                if (mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase(RECURSIVEFACTOR_N))
                    mutationFee = mutationFeeDetails.getFlatAmount();
                else {
                    excessDocValue = documentValue.subtract(mutationFeeDetails.getLowLimit())
                            .add(BigDecimal.ONE);
                    multiplicationFactor = excessDocValue.divide(mutationFeeDetails.getRecursiveAmount(),
                            BigDecimal.ROUND_CEILING);
                    mutationFee = mutationFeeDetails.getFlatAmount()
                            .add(multiplicationFactor.multiply(mutationFeeDetails.getRecursiveFactor()));
                }
            if (mutationFeeDetails.getPercentage() != null
                    && mutationFeeDetails.getPercentage().compareTo(ZERO) > 0)
                if (mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase(RECURSIVEFACTOR_N))
                    mutationFee = documentValue.multiply(mutationFeeDetails.getPercentage())
                            .divide(PropertyTaxConstants.BIGDECIMAL_100);
            mutationFee = mutationFee.setScale(0, BigDecimal.ROUND_HALF_UP);
        }
    }
    return RESULT_MUTATION_FEE;
}

From source file:com.nkapps.billing.dao.BankStatementDaoImpl.java

private void insertFizPaymentByDebtor(Session sessionTransaction, Validator validator, BankStatement bs,
        LocalDateTime dateTime, List<String> fizTins) throws Exception {
    BigDecimal fullSum = bs.getPaymentSum();
    BigDecimal keyCost = new BigDecimal(getKeyCost());
    int listSize = fizTins.size();
    int currentIndex = 0;

    for (String fizTin : fizTins) {
        currentIndex++;//from  w w w.  j a va 2s .  co  m
        BigDecimal currentSum;
        if (currentIndex == listSize || fullSum.compareTo(keyCost) < 0) {
            currentSum = fullSum;
            fullSum = BigDecimal.ZERO;
        } else {
            currentSum = keyCost;
            fullSum = fullSum.subtract(keyCost);
        }

        if (currentSum.compareTo(BigDecimal.ZERO) > 0) {
            String tinDebtor = fizTin.equals(bs.getTin()) ? null : bs.getTin();

            Payment payment = new Payment();
            payment.setTin(fizTin);
            payment.setPaymentNum(bs.getPaymentNum());
            payment.setPaymentDate(bs.getPaymentDate());
            payment.setPaymentSum(currentSum);
            payment.setSourceCode((short) 1);
            payment.setState((short) 1);
            payment.setTinDebtor(tinDebtor);
            payment.setClaim((short) 0);
            payment.setDateCreated(dateTime);
            payment.setDateUpdated(dateTime);

            Set<ConstraintViolation<Payment>> constraints = validator.validate(payment);
            if (constraints.isEmpty()) {
                sessionTransaction.save(payment);

                BankStatementPayment bsp = new BankStatementPayment();
                BankStatementPaymentId bspId = new BankStatementPaymentId();
                bspId.setBankStatement(bs);
                bspId.setPayment(payment);
                bsp.setId(bspId);

                sessionTransaction.save(bsp);

            } else {
                throw new Exception("payment isnot valid, tin = " + payment.getTin());
            }
        }
        if (fullSum.compareTo(BigDecimal.ZERO) <= 0) {
            break;
        }
    }

    bs.setTransfered((short) 1);
    sessionTransaction.update(bs);

}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The trigonometric co-tangent./*from  ww  w .  j av a2  s  . com*/
 *
 * @param x the argument in radians.
 * @return the cot(x)
 */
static public BigDecimal cot(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) == 0) {
        throw new ArithmeticException("Cannot take cot of zero " + x.toString());
    } else if (x.compareTo(BigDecimal.ZERO) < 0) {
        return cot(x.negate()).negate();
    } else {
        /* reduce modulo pi
         */
        BigDecimal res = modpi(x);
        /* absolute error in the result is err(x)/sin^2(x) to lowest order
         */
        final double xDbl = res.doubleValue();
        final double xUlpDbl = x.ulp().doubleValue() / 2.;
        final double eps = xUlpDbl / 2. / Math.pow(Math.sin(xDbl), 2.);
        final BigDecimal xhighpr = scalePrec(res, 2);
        final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr);
        MathContext mc = new MathContext(err2prec(xhighpr.doubleValue(), eps));
        BigDecimal resul = BigDecimal.ONE.divide(xhighpr, mc);
        /* x^(2i-1) */
        BigDecimal xpowi = xhighpr;
        Bernoulli b = new Bernoulli();
        /* 2^(2i) */
        BigInteger fourn = new BigInteger("4");
        /* (2i)! */
        BigInteger fac = BigInteger.ONE;
        for (int i = 1;; i++) {
            Rational f = b.at(2 * i);
            fac = fac.multiply(new BigInteger("" + (2 * i))).multiply(new BigInteger("" + (2 * i - 1)));
            f = f.multiply(fourn).divide(fac);
            BigDecimal c = multiplyRound(xpowi, f);
            if (i % 2 == 0) {
                resul = resul.add(c);
            } else {
                resul = resul.subtract(c);
            }
            if (Math.abs(c.doubleValue()) < 0.1 * eps) {
                break;
            }
            fourn = fourn.shiftLeft(2);
            xpowi = multiplyRound(xpowi, xhighprSq);
        }
        mc = new MathContext(err2prec(resul.doubleValue(), eps));
        return resul.round(mc);
    }
}

From source file:com.lp.server.artikel.ejbfac.WebshopItemServiceEjb.java

private void buildStockQuantities(WebshopItem webItem, Integer itemIId) throws RemoteException {
    BigDecimal lagerstand = getLagerFac().getLagerstandAllerLagerEinesMandanten(itemIId, false, webClientDto);
    webItem.setQuantityStored(lagerstand);

    BigDecimal fehlmengen = getFehlmengeFac().getAnzahlFehlmengeEinesArtikels(itemIId, webClientDto);
    BigDecimal reservierungen = getReservierungFac().getAnzahlReservierungen(itemIId, webClientDto);
    BigDecimal verfuegbar = lagerstand.subtract(reservierungen).subtract(fehlmengen);
    webItem.setQuantityAvailable(verfuegbar);
}

From source file:org.openbravo.advpaymentmngt.process.FIN_PaymentProcess.java

private void updateUsedCredit(FIN_Payment newPayment, String selectedCreditLineIds) {
    if (newPayment.getFINPaymentCreditList().isEmpty()) {
        // We process the payment from the Payment In/Out window (not from the Process Invoice flow)
        final BigDecimal usedAmount = newPayment.getUsedCredit();
        final BusinessPartner bp = newPayment.getBusinessPartner();
        final boolean isReceipt = newPayment.isReceipt();
        final Organization Org = newPayment.getOrganization();
        List<FIN_Payment> selectedCreditPayments = null;
        if (selectedCreditLineIds != null) {
            selectedCreditPayments = FIN_Utility.getOBObjectList(FIN_Payment.class, selectedCreditLineIds);
        }/*from   ww  w.ja v  a  2 s. co m*/
        final OBCriteria<FIN_Payment> reversepayment = OBDal.getInstance().createCriteria(FIN_Payment.class);
        reversepayment.add(Restrictions.eq(FIN_Payment.PROPERTY_REVERSEDPAYMENT, newPayment));
        final FIN_Payment reversepaymnt = (FIN_Payment) reversepayment.uniqueResult();

        List<FIN_Payment> creditPayments;
        if (reversepaymnt == null && selectedCreditLineIds == null) {
            // Normal scenario
            creditPayments = dao.getCustomerPaymentsWithCredit(Org, bp, isReceipt);
        } else if (selectedCreditLineIds != null) {
            creditPayments = selectedCreditPayments;
        } else {
            // If it is a reverse payment use its original payment
            creditPayments = new ArrayList<FIN_Payment>(1);
            creditPayments.add(reversepaymnt);
        }

        BigDecimal pendingToAllocateAmount = usedAmount;
        for (FIN_Payment creditPayment : creditPayments) {
            BigDecimal availableAmount = creditPayment.getGeneratedCredit()
                    .subtract(creditPayment.getUsedCredit());
            if (pendingToAllocateAmount.compareTo(availableAmount) == 1) {
                creditPayment.setUsedCredit(creditPayment.getUsedCredit().add(availableAmount));
                pendingToAllocateAmount = pendingToAllocateAmount.subtract(availableAmount);
                linkCreditPayment(newPayment, availableAmount, creditPayment);
                OBDal.getInstance().save(creditPayment);
            } else {
                creditPayment.setUsedCredit(creditPayment.getUsedCredit().add(pendingToAllocateAmount));
                linkCreditPayment(newPayment, pendingToAllocateAmount, creditPayment);
                OBDal.getInstance().save(creditPayment);
                break;
            }
        }
    }
}