Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_UP.

Prototype

RoundingMode HALF_UP

To view the source code for java.math RoundingMode HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:org.meveo.service.billing.impl.InvoiceService.java

public void recomputeAggregates(Invoice invoice, User currentUser) throws BusinessException {
    boolean entreprise = invoice.getProvider().isEntreprise();
    int rounding = invoice.getProvider().getRounding() == null ? 2 : invoice.getProvider().getRounding();
    BillingAccount billingAccount = billingAccountService.findById(invoice.getBillingAccount().getId());
    boolean exoneratedFromTaxes = billingAccountService.isExonerated(billingAccount);
    BigDecimal nonEnterprisePriceWithTax = BigDecimal.ZERO;

    Map<Long, TaxInvoiceAgregate> taxInvoiceAgregateMap = new HashMap<Long, TaxInvoiceAgregate>();
    List<SubCategoryInvoiceAgregate> subCategoryInvoiceAgregates = new ArrayList<SubCategoryInvoiceAgregate>();
    invoice.setAmountTax(null);/*  w w w. j  ava 2  s.c o  m*/
    invoice.setAmountWithoutTax(null);
    invoice.setAmountWithTax(null);

    // update the aggregated subcat of an invoice
    for (InvoiceAgregate invoiceAggregate : invoice.getInvoiceAgregates()) {
        if (invoiceAggregate instanceof CategoryInvoiceAgregate) {
            invoiceAggregate.resetAmounts();
        } else if (invoiceAggregate instanceof TaxInvoiceAgregate) {
            TaxInvoiceAgregate taxInvoiceAgregate = (TaxInvoiceAgregate) invoiceAggregate;
            taxInvoiceAgregateMap.put(taxInvoiceAgregate.getTax().getId(), taxInvoiceAgregate);
        } else if (invoiceAggregate instanceof SubCategoryInvoiceAgregate) {
            subCategoryInvoiceAgregates.add((SubCategoryInvoiceAgregate) invoiceAggregate);
        }
    }

    for (TaxInvoiceAgregate taxInvoiceAgregate : taxInvoiceAgregateMap.values()) {
        taxInvoiceAgregate.setAmountWithoutTax(new BigDecimal(0));
        for (SubCategoryInvoiceAgregate subCategoryInvoiceAgregate : subCategoryInvoiceAgregates) {
            if (subCategoryInvoiceAgregate.getQuantity().signum() != 0) {
                if (subCategoryInvoiceAgregate.getSubCategoryTaxes().contains(taxInvoiceAgregate.getTax())) {
                    taxInvoiceAgregate.addAmountWithoutTax(subCategoryInvoiceAgregate.getAmountWithoutTax());
                }
            }
        }

        taxInvoiceAgregate.setAmountTax(taxInvoiceAgregate.getAmountWithoutTax()
                .multiply(taxInvoiceAgregate.getTaxPercent()).divide(new BigDecimal("100")));
        // then round the tax
        taxInvoiceAgregate
                .setAmountTax(taxInvoiceAgregate.getAmountTax().setScale(rounding, RoundingMode.HALF_UP));

        taxInvoiceAgregate.setAmountWithTax(
                taxInvoiceAgregate.getAmountWithoutTax().add(taxInvoiceAgregate.getAmountTax()));
    }

    // update the amount with and without tax of all the tax aggregates in
    // each sub category aggregate
    SubCategoryInvoiceAgregate biggestSubCat = null;
    BigDecimal biggestAmount = new BigDecimal("-100000000");

    for (InvoiceAgregate invoiceAgregate : subCategoryInvoiceAgregates) {
        SubCategoryInvoiceAgregate subCategoryInvoiceAgregate = (SubCategoryInvoiceAgregate) invoiceAgregate;

        if (!entreprise) {
            nonEnterprisePriceWithTax = nonEnterprisePriceWithTax
                    .add(subCategoryInvoiceAgregate.getAmountWithTax());
        }

        subCategoryInvoiceAgregate.setAmountWithoutTax(subCategoryInvoiceAgregate.getAmountWithoutTax() != null
                ? subCategoryInvoiceAgregate.getAmountWithoutTax().setScale(rounding, RoundingMode.HALF_UP)
                : BigDecimal.ZERO);

        subCategoryInvoiceAgregate.getCategoryInvoiceAgregate()
                .addAmountWithoutTax(subCategoryInvoiceAgregate.getAmountWithoutTax());

        if (subCategoryInvoiceAgregate.getAmountWithoutTax().compareTo(biggestAmount) > 0) {
            biggestAmount = subCategoryInvoiceAgregate.getAmountWithoutTax();
            biggestSubCat = subCategoryInvoiceAgregate;
        }
    }

    for (InvoiceAgregate invoiceAgregate : invoice.getInvoiceAgregates()) {
        if (invoiceAgregate instanceof CategoryInvoiceAgregate) {
            CategoryInvoiceAgregate categoryInvoiceAgregate = (CategoryInvoiceAgregate) invoiceAgregate;
            invoice.addAmountWithoutTax(
                    categoryInvoiceAgregate.getAmountWithoutTax().setScale(rounding, RoundingMode.HALF_UP));
        }

        if (invoiceAgregate instanceof TaxInvoiceAgregate) {
            TaxInvoiceAgregate taxInvoiceAgregate = (TaxInvoiceAgregate) invoiceAgregate;
            invoice.addAmountTax(taxInvoiceAgregate.getAmountTax().setScale(rounding, RoundingMode.HALF_UP));
        }
    }

    if (invoice.getAmountWithoutTax() != null) {
        invoice.setAmountWithTax(invoice.getAmountWithoutTax()
                .add(invoice.getAmountTax() == null ? BigDecimal.ZERO : invoice.getAmountTax()));
    }

    if (!entreprise && biggestSubCat != null && !exoneratedFromTaxes) {
        BigDecimal delta = nonEnterprisePriceWithTax.subtract(invoice.getAmountWithTax());
        log.debug("delta={}-{}={}", nonEnterprisePriceWithTax, invoice.getAmountWithTax(), delta);

        biggestSubCat.setAmountWithoutTax(
                biggestSubCat.getAmountWithoutTax().add(delta).setScale(rounding, RoundingMode.HALF_UP));
        for (Tax tax : biggestSubCat.getSubCategoryTaxes()) {
            TaxInvoiceAgregate invoiceAgregateT = taxInvoiceAgregateMap.get(tax.getId());
            log.debug("tax3 ht={}", invoiceAgregateT.getAmountWithoutTax());

            invoiceAgregateT.setAmountWithoutTax(
                    invoiceAgregateT.getAmountWithoutTax().add(delta).setScale(rounding, RoundingMode.HALF_UP));
            log.debug("tax4 ht={}", invoiceAgregateT.getAmountWithoutTax());

        }

        CategoryInvoiceAgregate invoiceAgregateR = biggestSubCat.getCategoryInvoiceAgregate();
        invoiceAgregateR.setAmountWithoutTax(
                invoiceAgregateR.getAmountWithoutTax().add(delta).setScale(rounding, RoundingMode.HALF_UP));

        invoice.setAmountWithoutTax(
                invoice.getAmountWithoutTax().add(delta).setScale(rounding, RoundingMode.HALF_UP));
        invoice.setAmountWithTax(nonEnterprisePriceWithTax.setScale(rounding, RoundingMode.HALF_UP));
    }

    // calculate discounts here
    // no need to create discount aggregates we will use the one from
    // adjustedInvoice

    Object[] object = invoiceAgregateService.findTotalAmountsForDiscountAggregates(getLinkedInvoice(invoice));
    BigDecimal discountAmountWithoutTax = (BigDecimal) object[0];
    BigDecimal discountAmountTax = (BigDecimal) object[1];
    BigDecimal discountAmountWithTax = (BigDecimal) object[2];

    log.debug("discountAmountWithoutTax= {}, discountAmountTax={}, discountAmountWithTax={}", object[0],
            object[1], object[2]);

    invoice.addAmountWithoutTax(discountAmountWithoutTax);
    invoice.addAmountTax(discountAmountTax);
    invoice.addAmountWithTax(discountAmountWithTax);

    // compute net to pay
    BigDecimal netToPay = BigDecimal.ZERO;
    if (entreprise) {
        netToPay = invoice.getAmountWithTax();
    } else {
        BigDecimal balance = customerAccountService.customerAccountBalanceDue(null,
                invoice.getBillingAccount().getCustomerAccount().getCode(), invoice.getDueDate(),
                invoice.getProvider());

        if (balance == null) {
            throw new BusinessException("account balance calculation failed");
        }
        netToPay = invoice.getAmountWithTax().add(balance);
    }

    invoice.setNetToPay(netToPay);
}

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

/**
 * Analyse positions from ui./*from   w  w w  .  j a  v a  2s  . co m*/
 *
 * @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);
    }
}

From source file:sernet.gs.ui.rcp.main.bsi.views.FileView.java

private static double round(double value) {
    BigDecimal bd = new BigDecimal(value);
    return bd.setScale(3, RoundingMode.HALF_UP).doubleValue();
}

From source file:org.apache.calcite.runtime.SqlFunctions.java

/** SQL <code>ROUND</code> operator applied to BigDecimal values. */
public static BigDecimal sround(BigDecimal b0, int b1) {
    return b0.movePointRight(b1).setScale(0, RoundingMode.HALF_UP).movePointLeft(b1);
}

From source file:org.egov.works.web.actions.reports.ContractorwiseAbstractReportAction.java

private List<CommonDrillDownReportBean> generateEstimateList(final List<Object[]> objArrList) {
    final List<CommonDrillDownReportBean> beanList = new LinkedList<CommonDrillDownReportBean>();
    CommonDrillDownReportBean bean = null;
    BigDecimal amount = null;//w  w  w.j  a va2  s .  c o  m
    for (final Object[] objArr : objArrList) {
        bean = new CommonDrillDownReportBean();
        bean.setEstimateId(((BigDecimal) objArr[0]).longValue());
        bean.setEstNumber(objArr[1].toString());
        bean.setEstDate((Date) objArr[2]);
        bean.setEstName(objArr[3].toString());
        bean.setWardName(objArr[4].toString());
        bean.setEstApprovedDate((Date) objArr[5]);
        amount = (BigDecimal) objArr[6];
        if (amount != null)
            bean.setEstAmount(new BigDecimal(amount.toString()).setScale(2, RoundingMode.HALF_UP));
        beanList.add(bean);
    }
    return beanList;
}

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

@Override
protected void calculateNegativeStockCorrectionAdjustmentAmount(CostAdjustmentLine costAdjLine) {
    MaterialTransaction basetrx = costAdjLine.getInventoryTransaction();
    boolean areBaseTrxBackdatedFixed = getCostingRule().isBackdatedTransactionsFixed() && !CostingUtils
            .getCostingRuleFixBackdatedFrom(getCostingRule()).before(basetrx.getTransactionProcessDate());
    BigDecimal currentStock = CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBaseTrxBackdatedFixed);
    BigDecimal currentValueAmt = CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBaseTrxBackdatedFixed, getCostCurrency());

    Costing curCosting = basetrx.getMaterialMgmtCostingList().get(0);
    BigDecimal trxPrice = curCosting.getPrice();
    BigDecimal adjustAmt = currentStock.multiply(trxPrice).setScale(stdCurPrecission, RoundingMode.HALF_UP)
            .subtract(currentValueAmt);/*from   w  w w . ja v  a2s.  co  m*/

    costAdjLine.setCurrency((Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCostCurrencyId));
    costAdjLine.setAdjustmentAmount(adjustAmt);
    OBDal.getInstance().save(costAdjLine);
}

From source file:org.meveo.service.billing.impl.InvoiceService.java

public void recomputeSubCategoryAggregate(Invoice invoice, User currentUser) {
    int rounding = invoice.getBillingAccount().getProvider().getRounding() == null ? 2
            : invoice.getBillingAccount().getProvider().getRounding();

    List<TaxInvoiceAgregate> taxInvoiceAgregates = new ArrayList<TaxInvoiceAgregate>();
    List<SubCategoryInvoiceAgregate> subCategoryInvoiceAgregates = new ArrayList<SubCategoryInvoiceAgregate>();

    for (InvoiceAgregate invoiceAgregate : invoice.getInvoiceAgregates()) {
        if (invoiceAgregate instanceof TaxInvoiceAgregate) {
            taxInvoiceAgregates.add((TaxInvoiceAgregate) invoiceAgregate);
        } else if (invoiceAgregate instanceof SubCategoryInvoiceAgregate) {
            subCategoryInvoiceAgregates.add((SubCategoryInvoiceAgregate) invoiceAgregate);
        }// w w  w.  j  av a 2s .c  o  m
    }

    for (TaxInvoiceAgregate taxInvoiceAgregate : taxInvoiceAgregates) {
        taxInvoiceAgregate.setAmountWithoutTax(new BigDecimal(0));
        for (SubCategoryInvoiceAgregate subCategoryInvoiceAgregate : subCategoryInvoiceAgregates) {
            if (subCategoryInvoiceAgregate.getQuantity().signum() != 0) {
                if (subCategoryInvoiceAgregate.getSubCategoryTaxes().contains(taxInvoiceAgregate.getTax())) {
                    taxInvoiceAgregate.addAmountWithoutTax(subCategoryInvoiceAgregate.getAmountWithoutTax());
                }
            }
        }

        taxInvoiceAgregate.setAmountTax(taxInvoiceAgregate.getAmountWithoutTax()
                .multiply(taxInvoiceAgregate.getTaxPercent()).divide(new BigDecimal("100")));
        // then round the tax
        taxInvoiceAgregate
                .setAmountTax(taxInvoiceAgregate.getAmountTax().setScale(rounding, RoundingMode.HALF_UP));

        taxInvoiceAgregate.setAmountWithTax(
                taxInvoiceAgregate.getAmountWithoutTax().add(taxInvoiceAgregate.getAmountTax()));
    }
}

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
 *///from w w  w .  jav a  2 s  .  c o  m
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:org.kuali.kfs.module.ar.document.service.impl.ContractsGrantsInvoiceDocumentServiceImpl.java

/**
 * @param contractsGrantsInvoiceDocument
 * @param invoiceDetail//www. j  av a  2s.  co m
 */
protected void assignCurrentExpenditureToNonExistingAccountObjectCode(
        ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument,
        ContractsGrantsInvoiceDetail invoiceDetail) {
    String categoryCode = invoiceDetail.getCategoryCode();
    if (StringUtils.isBlank(categoryCode)) {
        throw new IllegalArgumentException(
                "Category Code can not be null during recalculation of account object code for Contracts & Grants Invoice Document.");
    }
    // get the category that matches this category code.
    final CostCategory category = businessObjectService.findBySinglePrimaryKey(CostCategory.class,
            categoryCode);

    // got the category now.
    if (!ObjectUtils.isNull(category)) {
        final KualiDecimal oneCent = new KualiDecimal(0.01);

        int size = contractsGrantsInvoiceDocument.getAccountDetails().size();
        KualiDecimal amount = new KualiDecimal(invoiceDetail.getInvoiceAmount().bigDecimalValue()
                .divide(new BigDecimal(size), 2, RoundingMode.HALF_UP));
        KualiDecimal remainder = invoiceDetail.getInvoiceAmount()
                .subtract(amount.multiply(new KualiDecimal(size)));

        for (InvoiceAccountDetail invoiceAccountDetail : contractsGrantsInvoiceDocument.getAccountDetails()) {
            InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode = new InvoiceDetailAccountObjectCode();
            invoiceDetailAccountObjectCode
                    .setDocumentNumber(contractsGrantsInvoiceDocument.getDocumentNumber());
            invoiceDetailAccountObjectCode.setProposalNumber(
                    contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getProposalNumber());
            invoiceDetailAccountObjectCode.setCategoryCode(categoryCode);
            invoiceDetailAccountObjectCode.setAccountNumber(invoiceAccountDetail.getAccountNumber());
            invoiceDetailAccountObjectCode
                    .setChartOfAccountsCode(invoiceAccountDetail.getChartOfAccountsCode());
            invoiceDetailAccountObjectCode.setCumulativeExpenditures(KualiDecimal.ZERO); // it's 0.00 that's why we are in this section to begin with.
            invoiceDetailAccountObjectCode.setTotalBilled(KualiDecimal.ZERO); // this is also 0.00 because it has never been billed before
            final ObjectCodeCurrent objectCode = getCostCategoryService().findObjectCodeForChartAndCategory(
                    invoiceAccountDetail.getChartOfAccountsCode(), categoryCode);
            if (!ObjectUtils.isNull(objectCode)) {
                invoiceDetailAccountObjectCode.setFinancialObjectCode(objectCode.getFinancialObjectCode());
            }

            // tack on or remove one penny until the remainder is 0 - take a penny, leave a penny!
            if (remainder.isGreaterThan(KualiDecimal.ZERO)) {
                amount = amount.add(oneCent);
                remainder = remainder.subtract(oneCent);
            } else if (remainder.isLessThan(KualiDecimal.ZERO)) {
                amount = amount.subtract(oneCent);
                remainder = remainder.add(oneCent);
            }
            invoiceDetailAccountObjectCode.setCurrentExpenditures(amount);

            List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes = contractsGrantsInvoiceDocument
                    .getInvoiceDetailAccountObjectCodes();
            if (invoiceDetailAccountObjectCodes.contains(invoiceDetailAccountObjectCode)) {
                // update existing code
                InvoiceDetailAccountObjectCode original = invoiceDetailAccountObjectCodes
                        .get(invoiceDetailAccountObjectCodes.indexOf(invoiceDetailAccountObjectCode));
                original.setCurrentExpenditures(amount);
                original.setCategoryCode(categoryCode);
            } else {
                // add this single account object code item to the list in the Map
                contractsGrantsInvoiceDocument.getInvoiceDetailAccountObjectCodes()
                        .add(invoiceDetailAccountObjectCode);
            }
        }
    } else {
        LOG.error(
                "Category Code cannot be found from the category list during recalculation of account object code for Contracts & Grants Invoice Document.");
    }
}