Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

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

Prototype

public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose scale is as specified.

Usage

From source file:org.kuali.kfs.module.tem.document.service.impl.TravelReimbursementServiceImpl.java

/**
 * Calculates how much each of the given accounting lines contributes to the total of the accounting lines
 * @param accountingLines the accounting lines to find the percentage contribution of each of
 * @return a List of the accounting lines and their corresponding percentages
 *///from  w  ww .j  av  a 2s .com
@Override
public List<TemSourceAccountingLineTotalPercentage> getPercentagesForLines(
        List<TemSourceAccountingLine> accountingLines) {
    final BigDecimal total = calculateLinesTotal(accountingLines).bigDecimalValue();
    List<TemSourceAccountingLineTotalPercentage> linePercentages = new ArrayList<TemSourceAccountingLineTotalPercentage>();
    for (TemSourceAccountingLine accountingLine : accountingLines) {
        final BigDecimal accountingLineAmount = accountingLine.getAmount().bigDecimalValue();
        final BigDecimal percentage = accountingLineAmount.divide(total,
                getDistributionScale(accountingLineAmount, total), BigDecimal.ROUND_HALF_UP);
        final TemSourceAccountingLineTotalPercentage linePercentage = new TemSourceAccountingLineTotalPercentage(
                accountingLine, percentage);
        linePercentages.add(linePercentage);
    }
    return linePercentages;
}

From source file:org.kuali.kfs.module.bc.document.service.impl.SalarySettingServiceImpl.java

/**
 * @see org.kuali.kfs.module.bc.document.service.SalarySettingService#calculateCSFFteQuantity(java.lang.Integer,
 *      java.lang.Integer, java.math.BigDecimal)
 *///from  w  w w .j  a  v  a  2 s  .  c om
public BigDecimal calculateCSFFteQuantity(Integer payMonth, Integer normalWorkMonth,
        BigDecimal requestedCSFTimePercent) {
    LOG.debug("calculateCSFFteQuantity() start");

    if (payMonth == null || normalWorkMonth == null || requestedCSFTimePercent == null) {
        return BigDecimal.ZERO;
    }

    BigDecimal payMonthAsDecimal = BigDecimal.valueOf(payMonth);
    BigDecimal normalMonthAsDecimal = BigDecimal.valueOf(normalWorkMonth);
    BigDecimal fundingMonthPercent = normalMonthAsDecimal.divide(payMonthAsDecimal, 5,
            BigDecimal.ROUND_HALF_UP);

    BigDecimal fteQuantity = requestedCSFTimePercent.multiply(fundingMonthPercent)
            .divide(KFSConstants.ONE_HUNDRED.bigDecimalValue());

    return fteQuantity.setScale(5, BigDecimal.ROUND_HALF_UP);
}

From source file:org.opentaps.common.util.UtilCommon.java

/**
 * Given a set of values, calculates the correspondent % of total.
 *
 * @param values a <code>Map</code> of values, such as customer/vendor balance values
 * @param minPercentage the minimum percentage to consider for calculation purposes
 * @param locale the <code>Locale</code> used to build the label strings
 * @return returns the weight (percentage) of each balance
 *//*ww w  .j  av  a  2s  .  com*/
public static List<Map<String, Number>> getPercentageValues(Map<String, BigDecimal> values,
        BigDecimal minPercentage, Locale locale) {

    Collection<BigDecimal> inValues = values.values();
    Set<String> keys = values.keySet();
    List<Map<String, Number>> list = new LinkedList<Map<String, Number>>();
    BigDecimal total = BigDecimal.ZERO;
    BigDecimal othersTotal = BigDecimal.ZERO;
    final int decimals = 2; // precision for the percentage values

    // total up all the values
    for (BigDecimal value : inValues) {
        total = total.add(value);
    }

    if (total.signum() > 0) { //prevent division by zero
        for (String key : keys) {
            BigDecimal value = values.get(key);
            value = value.divide(total, 10, RoundingMode.HALF_UP);
            if (value.compareTo(minPercentage) == 1) { //greater than minPercentage?
                Map<String, Number> map = FastMap.newInstance();
                value = value.multiply(new BigDecimal(100)).setScale(decimals, RoundingMode.HALF_UP); //display only 2 decimal places
                map.put(key, value);
                list.add(map);
            } else {
                othersTotal = othersTotal.add(value).setScale(decimals + 3, RoundingMode.HALF_UP);
            }
        }

        // normalize to % - ie 0.577 to 57.7
        othersTotal = othersTotal.multiply(new BigDecimal(100)).setScale(decimals, RoundingMode.HALF_UP);
        if (othersTotal.signum() > 0) {
            list.add(UtilMisc.<String, Number>toMap(UtilMessage.expandLabel("CommonOther", locale)
                    + String.format(" (%1$s%%)", othersTotal.toString()), othersTotal));
        }
    }

    return list;
}

From source file:com.dp2345.entity.Cart.java

/**
 * ?/*  w w  w .  ja v  a 2  s  .  c  om*/
 * 
 * @return 
 */
@Transient
public BigDecimal getDiscount() {
    BigDecimal originalPrice = new BigDecimal(0);
    BigDecimal currentPrice = new BigDecimal(0);
    for (Promotion promotion : getPromotions()) {
        if (promotion != null) {
            int promotionQuantity = getQuantity(promotion);
            BigDecimal originalPromotionPrice = getTempPrice(promotion);
            BigDecimal currentPromotionPrice = promotion.calculatePrice(promotionQuantity,
                    originalPromotionPrice);
            originalPrice = originalPrice.add(originalPromotionPrice);
            currentPrice = currentPrice.add(currentPromotionPrice);
            Set<CartItem> cartItems = getCartItems(promotion);
            for (CartItem cartItem : cartItems) {
                if (cartItem != null && cartItem.getTempPrice() != null) {
                    BigDecimal tempPrice;
                    if (originalPromotionPrice.compareTo(new BigDecimal(0)) > 0) {
                        tempPrice = currentPromotionPrice.divide(originalPromotionPrice, 50, RoundingMode.DOWN)
                                .multiply(cartItem.getTempPrice());
                    } else {
                        tempPrice = new BigDecimal(0);
                    }
                    cartItem.setTempPrice(
                            tempPrice.compareTo(new BigDecimal(0)) > 0 ? tempPrice : new BigDecimal(0));
                }
            }
        }
    }
    if (getCartItems() != null) {
        for (CartItem cartItem : getCartItems()) {
            if (cartItem != null) {
                cartItem.setTempPrice(null);
            }
        }
    }
    Setting setting = SettingUtils.get();
    BigDecimal discount = setting.setScale(originalPrice.subtract(currentPrice));
    return discount.compareTo(new BigDecimal(0)) > 0 ? discount : new BigDecimal(0);
}

From source file:coffeshop.PaymentPage.java

private void generateQR(String btcPay) throws Exception {
    BigDecimal dollar = new BigDecimal(btcPay);
    BigDecimal btcPriceIndex = btcPriceIndex();
    BigDecimal btc = dollar.divide(btcPriceIndex, 5, BigDecimal.ROUND_HALF_UP);
    byte[] imageInByte;
    BufferedImage originalImage = ImageIO.read(new File("src/ImageRes/QR.jpg"));
    String details = "bitcoin:12nAq7bJSkKFxJYaHjhjfPAaZ6sXgLqBJ7?amount=" + btc;
    QRCode.from(details).withSize(125, 125).file();
    QRCode.from(details).withSize(125, 125).stream();
    ByteArrayOutputStream out = QRCode.from(details).to(ImageType.JPG).stream();
    ImageIO.write(originalImage, "jpg", out);
    out.flush();//from   w  w w  . ja  va2 s  .c o  m
    imageInByte = out.toByteArray();
    out.close();
    InputStream in = new ByteArrayInputStream(imageInByte);
    BufferedImage bImageFromConvert = ImageIO.read(in);
    ImageIO.write(bImageFromConvert, "jpg", new File("src/ImageRes/QR.jpg"));
}

From source file:coffeshop.PaymentPage.java

private void btnScanBTCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnScanBTCActionPerformed
    timeStop = false;// www  .  j  av a 2 s .  com
    btnScanBTC.setEnabled(false);
    btcTimer();
    String btcPay = txtPayAmt.getText();
    BigDecimal USD = new BigDecimal(btcPay);
    BigDecimal USDtoBTC = btcPriceIndex();
    BigDecimal BTCDue = USD.divide(USDtoBTC, 5, BigDecimal.ROUND_HALF_UP);
    USDtoBTC = USDtoBTC.setScale(2, BigDecimal.ROUND_HALF_UP);
    lblUSDtoBTC.setText("USD/BTC = " + USDtoBTC);
    lblBTCDue.setText("BTC Due: " + BTCDue);
    try {
        generateQR(btcPay);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error generating QR Code");
        ex.printStackTrace();
    }
    try {
        BufferedImage image = ImageIO.read(new File("src/ImageRes/QR.jpg"));
        ImageIcon icon = new ImageIcon(image);
        icon.getImage().flush();
        lblQRC.setIcon(icon);
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }

    if (lblQRC.getIcon() == null) {
        lblQRC.setIcon(defaultQR);
        JOptionPane.showMessageDialog(null, "Wrong QR Code. Please try again.", "Wrong QR Code",
                JOptionPane.PLAIN_MESSAGE);
    }
}

From source file:com.lp.server.artikel.fastlanereader.ArtikellisteHandler.java

public QueryResult getPageAt(Integer rowIndex) throws EJBExceptionLP {

    QueryResult result = null;//from www .j a  v a2s.c  o  m
    SessionFactory factory = FLRSessionFactory.getFactory();
    Session session = null;

    Iterator resultListIterator = null;
    List resultList = null;

    try {
        int colCount = getTableInfo().getColumnClasses().length;
        int pageSize = getLimit();
        int startIndex = Math.max(rowIndex.intValue() - (pageSize / 2), 0);

        int endIndex = startIndex + pageSize - 1;

        session = factory.openSession();
        session = setFilter(session);

        String queryString = "SELECT artikelliste.i_id FROM FLRArtikelliste AS artikelliste "
                + " LEFT OUTER JOIN artikelliste.artikellagerset AS alager "
                + " LEFT OUTER JOIN artikelliste.flrgeometrie AS geo "
                + " LEFT OUTER JOIN artikelliste.artikellieferantset AS artikellieferantset "
                + " LEFT OUTER JOIN artikelliste.stuecklisten AS stuecklisten "
                + " LEFT OUTER JOIN artikelliste.artikelsprset AS aspr "
                + " LEFT OUTER JOIN artikelliste.flrartikelgruppe AS ag "
                + " LEFT OUTER JOIN artikelliste.flrartikelklasse AS ak " + this.buildWhereClause()
                + this.buildGroupByClause() + this.buildOrderByClause();

        Query query = session.createQuery(queryString);
        query.setFirstResult(startIndex);
        query.setMaxResults(pageSize);

        resultList = query.list();
        Object[][] rows = new Object[resultList.size()][colCount];

        Integer[] iIds = new Integer[resultList.size()];

        iIds = (Integer[]) resultList.toArray(iIds);

        String in = "";
        String inArtikel_i_id = "";

        HashMap hmRabattsatzFixpreis = new HashMap();
        HashMap hmPreisbasis = new HashMap();
        HashMap<Integer, String> hmKommentarTooltip = new HashMap<Integer, String>();

        if (resultList.size() > 0) {
            in = " AND artikelliste.i_id IN(";
            inArtikel_i_id = " pl.artikel_i_id IN(";
            String inKommentar = " ko.artikelkommentar.artikel_i_id IN(";

            for (int i = 0; i < iIds.length; i++) {
                if (i == iIds.length - 1) {
                    in += iIds[i];
                    inArtikel_i_id += iIds[i];
                    inKommentar += iIds[i];
                } else {
                    in += iIds[i] + ",";
                    inArtikel_i_id += iIds[i] + ",";
                    inKommentar += iIds[i] + ",";
                }
            }
            in += ") ";
            inArtikel_i_id += ") ";
            inKommentar += ") ";

            // String ins = StringUtils.join(iIds, ",") ;

            session.close();
            session = factory.openSession();
            session = setFilter(session);
            queryString = this.getFromClause() + this.buildWhereClause() + in + this.buildGroupByClause()
                    + this.buildOrderByClause();
            query = session.createQuery(queryString);
            resultList = query.list();

            Session sessionVkPreisBasis = factory.openSession();
            String rabattsatzFixpreis = "SELECT pl.artikel_i_id, pl.n_artikelstandardrabattsatz ,pl.n_artikelfixpreis FROM FLRVkpfartikelpreis AS pl  WHERE pl.vkpfartikelpreisliste_i_id="
                    + vkPreisliste + " AND " + inArtikel_i_id + "  ORDER BY t_preisgueltigab DESC ";
            Query queryRabattsatzFixpreis = sessionVkPreisBasis.createQuery(rabattsatzFixpreis);

            List resultListRabattsatzFixpreis = queryRabattsatzFixpreis.list();

            Iterator resultListIteratorRabattsatzFixpreis = resultListRabattsatzFixpreis.iterator();
            while (resultListIteratorRabattsatzFixpreis.hasNext()) {
                Object[] o = (Object[]) resultListIteratorRabattsatzFixpreis.next();
                if (!hmRabattsatzFixpreis.containsKey(o[0])) {
                    hmRabattsatzFixpreis.put(o[0], o);
                }

            }
            sessionVkPreisBasis.close();

            sessionVkPreisBasis = factory.openSession();
            String preisbasis;
            if (bVkPreisLief1preis) {
                preisbasis = "SELECT pl.artikel_i_id, pl.n_nettopreis FROM FLRArtikellieferant AS pl WHERE "
                        + inArtikel_i_id + " ORDER BY i_sort ASC ";
            } else {
                preisbasis = "SELECT pl.artikel_i_id, pl.n_verkaufspreisbasis FROM FLRVkpfartikelverkaufspreisbasis AS pl  WHERE "
                        + inArtikel_i_id + " AND t_verkaufspreisbasisgueltigab <='"
                        + Helper.formatDateWithSlashes(new java.sql.Date(System.currentTimeMillis())) + "'"
                        + "  ORDER BY t_verkaufspreisbasisgueltigab DESC ";
            }
            Query queryPreisbasis = sessionVkPreisBasis.createQuery(preisbasis);

            List resultListPreisbasis = queryPreisbasis.list();

            Iterator resultListIteratorPreisbasis = resultListPreisbasis.iterator();
            while (resultListIteratorPreisbasis.hasNext()) {
                Object[] o = (Object[]) resultListIteratorPreisbasis.next();
                if (!hmPreisbasis.containsKey(o[0])) {
                    hmPreisbasis.put(o[0], o[1]);
                }

            }
            sessionVkPreisBasis.close();

            // PJ18025
            sessionVkPreisBasis = factory.openSession();
            String kommentare = "SELECT ko.artikelkommentar.artikel_i_id, ko.x_kommentar, ko.artikelkommentar.flrartikelkommentarart.c_nr FROM FLRArtikelkommentarspr AS ko WHERE "
                    + inKommentar + " AND ko.locale='" + theClientDto.getLocUiAsString()
                    + "' AND ko.artikelkommentar.flrartikelkommentarart.b_tooltip=1 ";

            Query queryKommentare = sessionVkPreisBasis.createQuery(kommentare);

            List resultListKommentare = queryKommentare.list();

            Iterator resultListIteratorKommentare = resultListKommentare.iterator();
            while (resultListIteratorKommentare.hasNext()) {
                Object[] o = (Object[]) resultListIteratorKommentare.next();

                if (o[2] != null) {
                    String kommentar = "<b>" + (String) o[2] + ":</b>\n" + (String) o[1];

                    String kommentarVorhanden = "";
                    if (hmKommentarTooltip.containsKey(o[0])) {
                        kommentarVorhanden = hmKommentarTooltip.get(o[0]) + "<br><br>" + kommentar;
                    } else {
                        kommentarVorhanden = kommentar;
                    }

                    hmKommentarTooltip.put((Integer) o[0], kommentarVorhanden);
                }

            }
            sessionVkPreisBasis.close();

        }

        rows = new Object[resultList.size()][colCount];

        resultListIterator = resultList.iterator();

        int row = 0;

        String[] tooltipData = new String[resultList.size()];

        while (resultListIterator.hasNext()) {
            Object o[] = (Object[]) resultListIterator.next();

            Object[] rowToAddCandidate = new Object[colCount];

            rowToAddCandidate[getTableColumnInformation().getViewIndex("i_id")] = o[0];
            rowToAddCandidate[getTableColumnInformation().getViewIndex("artikel.artikelnummerlang")] = o[1];
            rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.stuecklistenart")] = o[13] != null
                    ? ((String) o[13]).trim()
                    : o[13];

            if (bKurzbezeichnungAnzeigen) {
                prepareKurzbezeichnung(o, rowToAddCandidate);
            }

            rowToAddCandidate[getTableColumnInformation().getViewIndex("bes.artikelbezeichnung")] = o[2];

            if (bAbmessungenStattZusatzbezeichnung || bArtikelgruppeStattZusatzbezeichnung) {
                if (bAbmessungenStattZusatzbezeichnung) {
                    prepareAbmessungen(o, rowToAddCandidate);
                } else {
                    prepareArtikelGruppeInAbmessung(o, rowToAddCandidate);
                }
            } else {
                rowToAddCandidate[getTableColumnInformation().getViewIndex("artikel.zusatzbez")] = o[6];
            }

            if (bArtikelgruppeAnzeigen) {
                prepareArtikelGruppe(o, rowToAddCandidate);
            } else {
                if (bArtikelklasseAnzeigen) {
                    prepareArtikelKlasse(o, rowToAddCandidate);
                }
            }

            if (bVkPreisStattGestpreis == true) {
                prepareVkPreis(hmRabattsatzFixpreis, hmPreisbasis, o, rowToAddCandidate);
            }

            if (o[4] != null && Helper.short2boolean((Short) o[5])) {
                rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.lagerstand")] = o[3];
            } else {
                rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.lagerstand")] = new BigDecimal(
                        0);
            }

            if (bLagerplaetzeAnzeigen) {
                prepareLagerplaetze((Integer) o[0], rowToAddCandidate);
            }

            if (bDarfPreiseSehen) {
                // Gestehungspreis holen
                BigDecimal gestehungspreis = (BigDecimal) o[4];
                if (gestehungspreis != null && ((BigDecimal) rowToAddCandidate[getTableColumnInformation()
                        .getViewIndex("lp.lagerstand")]).doubleValue() > 0) {
                    gestehungspreis = gestehungspreis.divide(
                            new BigDecimal(((BigDecimal) rowToAddCandidate[getTableColumnInformation()
                                    .getViewIndex("lp.lagerstand")]).doubleValue()),
                            4, BigDecimal.ROUND_HALF_EVEN);
                } else {
                    // Projekt 10870: WH: Wenn kein Gestpreis zustandekommt,
                    // dann Gestpreis des Hauptlagers anzeigen
                    if (Helper.short2boolean((Short) o[5]) && o[8] != null) {
                        gestehungspreis = (BigDecimal) o[8];
                    } else {
                        gestehungspreis = new BigDecimal(0);
                    }
                }
                if (bVkPreisStattGestpreis == false) {
                    rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.preis")] = gestehungspreis;
                }
            } else {
                rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.preis")] = new BigDecimal(0);
            }

            Long lAnzahlReklamationen = (Long) o[15];
            Boolean hatOffeneReklamationen = (lAnzahlReklamationen != null)
                    && lAnzahlReklamationen.intValue() > 0;

            FLRArtikelsperren as = (FLRArtikelsperren) o[7];

            if (as != null || hatOffeneReklamationen) {
                String gesperrt = null;

                if (as != null) {
                    gesperrt = as.getFlrsperren().getC_bez();
                }

                if (hatOffeneReklamationen) {
                    rowToAddCandidate[getTableColumnInformation()
                            .getViewIndex("Icon")] = getStatusMitUebersetzung(gesperrt,
                                    new java.sql.Timestamp(System.currentTimeMillis()), "R");
                } else {
                    rowToAddCandidate[getTableColumnInformation().getViewIndex("Icon")] = gesperrt;
                }

            }

            if (!Helper.short2boolean((Short) o[18])) {
                rowToAddCandidate[getTableColumnInformation().getViewIndex("Color")] = new Color(0, 0, 255);
            }

            rows[row] = rowToAddCandidate;

            // PJ18025
            String tooltip = (String) hmKommentarTooltip.get(o[0]);
            if (tooltip != null) {
                String text = tooltip;
                text = text.replaceAll("\n", "<br>");
                text = "<html>" + text + "</html>";
                tooltipData[row] = text;
            }

            row++;
        }
        result = new QueryResult(rows, getRowCount(), startIndex, endIndex, 0, tooltipData);
    } catch (Exception e) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e);
    } finally {
        closeSession(session);
    }
    return result;
}

From source file:org.openbravo.costing.CostingMigrationProcess.java

private void calculateCosts(Organization org) {
    Currency cur = FinancialUtils.getLegalEntityCurrency(org);
    String curId = cur.getId();//from ww  w .  jav  a2s.c  o  m
    Set<String> orgs = OBContext.getOBContext().getOrganizationStructureProvider(org.getClient().getId())
            .getChildTree(org.getId(), true);
    String orgId = org.getId();

    int costPrecision = cur.getCostingPrecision().intValue();
    int stdPrecision = cur.getStandardPrecision().intValue();
    CostingRuleProcess crp = new CostingRuleProcess();
    // Update cost of inventories and process starting physical inventories.
    ScrollableResults icls = getCloseInventoryLines(orgs);
    String productId = "";
    BigDecimal totalCost = BigDecimal.ZERO;
    BigDecimal totalStock = BigDecimal.ZERO;
    int i = 0;
    try {
        while (icls.next()) {
            InventoryCountLine icl = (InventoryCountLine) icls.get(0);
            if (!productId.equals(icl.getProduct().getId())) {
                productId = icl.getProduct().getId();
                HashMap<String, BigDecimal> stock = getCurrentValuedStock(productId, curId, orgs, orgId);
                totalCost = stock.get("cost");
                totalStock = stock.get("stock");
            }

            MaterialTransaction trx = crp.getInventoryLineTransaction(icl);
            trx.setTransactionProcessDate(DateUtils.addSeconds(trx.getTransactionProcessDate(), -1));
            trx.setCurrency(OBDal.getInstance().get(Currency.class, curId));

            BigDecimal trxCost = BigDecimal.ZERO;
            if (totalStock.compareTo(BigDecimal.ZERO) != 0) {
                trxCost = totalCost.multiply(trx.getMovementQuantity().abs()).divide(totalStock, stdPrecision,
                        BigDecimal.ROUND_HALF_UP);
            }
            if (trx.getMovementQuantity().compareTo(totalStock) == 0) {
                // Last transaction adjusts remaining cost amount.
                trxCost = totalCost;
            }
            trx.setTransactionCost(trxCost);
            trx.setCostCalculated(true);
            trx.setCostingStatus("CC");
            OBDal.getInstance().save(trx);
            Currency legalEntityCur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
            BigDecimal cost = BigDecimal.ZERO;
            if (BigDecimal.ZERO.compareTo(trx.getMovementQuantity()) != 0) {
                cost = trxCost.divide(trx.getMovementQuantity().abs(), costPrecision, BigDecimal.ROUND_HALF_UP);
            }
            if (!legalEntityCur.equals(cur)) {
                cost = FinancialUtils.getConvertedAmount(cost, cur, legalEntityCur, new Date(),
                        icl.getOrganization(), FinancialUtils.PRECISION_COSTING);
            }

            InventoryCountLine initICL = icl.getRelatedInventory();
            initICL.setCost(cost);
            OBDal.getInstance().save(initICL);

            totalCost = totalCost.subtract(trxCost);
            // MovementQty is already negative so add to totalStock to decrease it.
            totalStock = totalStock.add(trx.getMovementQuantity());

            if ((i % 100) == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
                cur = OBDal.getInstance().get(Currency.class, curId);
            }
            i++;
        }
    } finally {
        icls.close();
    }

    OBDal.getInstance().flush();
    insertTrxCosts();

}

From source file:org.kuali.kfs.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * @see org.kuali.kfs.module.purap.service.PurapAccountingService#generateAccountDistributionForProrationWithZeroTotal(java.util.List,
 *      java.lang.Integer)//from  w  w  w  .j  a va2  s . c o  m
 */
@Override
public List<PurApAccountingLine> generateAccountDistributionForProrationWithZeroTotal(
        PurchasingAccountsPayableDocument purapDoc) {
    String methodName = "generateAccountDistributionForProrationWithZeroTotal()";
    if (LOG.isDebugEnabled()) {
        LOG.debug(methodName + " started");
    }

    List<PurApAccountingLine> accounts = generatePercentSummary(purapDoc);

    // find the total percent and strip trailing zeros
    BigDecimal totalPercentValue = BigDecimal.ZERO;
    for (PurApAccountingLine accountingLine : accounts) {
        BigDecimal linePercent = BigDecimal.ZERO;
        if (ObjectUtils.isNotNull(accountingLine.getAccountLinePercent())) {
            linePercent = accountingLine.getAccountLinePercent();
        }

        totalPercentValue = totalPercentValue.add(linePercent).movePointLeft(2).stripTrailingZeros()
                .movePointRight(2);
    }

    if ((BigDecimal.ZERO.compareTo(totalPercentValue.remainder(ONE_HUNDRED))) != 0) {
        throwRuntimeException(methodName, "Invalid Percent Total of '" + totalPercentValue
                + "' does not allow for account distribution (must be multiple of 100)");
    }

    List newAccounts = new ArrayList();
    BigDecimal logDisplayOnlyTotal = BigDecimal.ZERO;
    BigDecimal percentUsed = BigDecimal.ZERO;
    int accountListSize = accounts.size();
    int i = 0;
    for (PurApAccountingLine accountingLine : accounts) {
        i++;
        BigDecimal percentToUse = BigDecimal.ZERO;
        KualiDecimal amt = KualiDecimal.ZERO;

        if (ObjectUtils.isNotNull(accountingLine.getAmount())) {
            amt = accountingLine.getAmount();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " " + accountingLine.getChartOfAccountsCode() + "-"
                    + accountingLine.getAccountNumber() + " " + amt + "/" + percentToUse);
        }

        // if it's the last account make up the leftover percent
        BigDecimal acctPercent = BigDecimal.ZERO;
        if (ObjectUtils.isNotNull(accountingLine.getAccountLinePercent())) {
            acctPercent = accountingLine.getAccountLinePercent();
        }

        if ((i != accountListSize) || (accountListSize == 1)) {
            // this account is not the last account or there is only one account
            percentToUse = (acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE))
                    .multiply(ONE_HUNDRED);
            percentUsed = percentUsed
                    .add(((acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE)))
                            .multiply(ONE_HUNDRED));
        } else {
            // this account is the last account so we have to makeup whatever is left out of 100
            percentToUse = ONE_HUNDRED.subtract(percentUsed);
        }

        PurApAccountingLine newAccountingLine = accountingLine.createBlankAmountsCopy();
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " pct = " + percentToUse);
        }
        newAccountingLine
                .setAccountLinePercent(percentToUse.setScale(acctPercent.scale(), BIG_DECIMAL_ROUNDING_MODE));
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " adding " + newAccountingLine.getAccountLinePercent());
        }
        newAccounts.add(newAccountingLine);
        logDisplayOnlyTotal = logDisplayOnlyTotal.add(newAccountingLine.getAccountLinePercent());
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " total = " + logDisplayOnlyTotal);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(methodName + " ended");
    }
    return newAccounts;
}

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

public static BigDecimal applyRate(BigDecimal _amount, ConversionRateDoc conversionRateDoc, boolean multiply) {
    BigDecimal amount = _amount;
    if (multiply) {
        return amount.multiply(conversionRateDoc.getRate());
    } else {/* w w w . j  a  va 2s  .  c o m*/
        return amount.divide(conversionRateDoc.getRate(), 6, BigDecimal.ROUND_HALF_EVEN);
    }
}