Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

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

Prototype

int ROUND_HALF_UP

To view the source code for java.math BigDecimal ROUND_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.egov.ptis.domain.service.property.VacancyRemissionService.java

private BigDecimal getNewTax(Ptdemand currPtDemand, BigDecimal newTax, final Installment installmentHalf) {
    if (currPtDemand != null)
        for (final EgDemandDetails dmdDet : currPtDemand.getEgDemandDetails())
            if (dmdDet.getInstallmentStartDate().equals(installmentHalf.getFromDate())
                    && !DEMANDRSN_CODE_PENALTY_FINES
                            .equals(dmdDet.getEgDemandReason().getEgDemandReasonMaster().getCode())) {
                newTax = newTax.add(// w  ww  .j  a v  a 2s  .c  o  m
                        dmdDet.getAmount().divide(new BigDecimal("2")).setScale(0, BigDecimal.ROUND_HALF_UP));
            }
    return newTax;
}

From source file:org.egov.adtax.service.AdvertisementDemandService.java

public Map<String, BigDecimal> checkPendingAmountByDemand(final AdvertisementPermitDetail advPermitDetail) {
    final Map<String, BigDecimal> demandFeeType = new LinkedHashMap<>();
    BigDecimal totalDemand = BigDecimal.ZERO;
    BigDecimal totalCollection = BigDecimal.ZERO;
    BigDecimal totalPending = BigDecimal.ZERO;
    BigDecimal penaltyAmount = BigDecimal.ZERO;
    BigDecimal additionalTaxAmount = BigDecimal.ZERO;
    if (advPermitDetail != null && advPermitDetail.getAdvertisement() != null
            && advPermitDetail.getAdvertisement().getDemandId() != null) {
        for (final EgDemandDetails demandDtl : advPermitDetail.getAdvertisement().getDemandId()
                .getEgDemandDetails()) {
            totalDemand = totalDemand.add(demandDtl.getAmount());
            totalCollection = totalCollection.add(demandDtl.getAmtCollected());
            totalPending = totalPending.add(demandDtl.getAmount().subtract(demandDtl.getAmtCollected()));
        }// w w  w  .  jav  a2  s.co  m
        penaltyAmount = advertisementPenaltyCalculator.calculatePenalty(advPermitDetail);
        additionalTaxAmount = advertisementAdditionalTaxCalculator
                .getTotalAdditionalTaxesByPassingAdvertisementPermit(advPermitDetail);

    }
    totalDemand = totalDemand.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    totalCollection = totalCollection.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    totalPending = totalPending.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    penaltyAmount = penaltyAmount.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    demandFeeType.put(AdvertisementTaxConstants.PENDINGDEMANDAMOUNT, totalPending);
    demandFeeType.put(AdvertisementTaxConstants.TOTAL_DEMAND, totalDemand);
    demandFeeType.put(AdvertisementTaxConstants.TOTALCOLLECTION, totalCollection);
    demandFeeType.put(AdvertisementTaxConstants.PENALTYAMOUNT, penaltyAmount);
    demandFeeType.put(AdvertisementTaxConstants.ADDITIONALTAXAMOUNT,
            additionalTaxAmount.setScale(0, BigDecimal.ROUND_HALF_UP));
    return demandFeeType;
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

protected LayerPriceComposition calculateLayerPriceComposition(DataWrapper dw, ExtLayerCalculator lc,
        String spAbbr, String layerName) throws Exception {
    String operation = dw.getOperation();
    if (operation == null) {
        log.error("Operation can not be null");
        throw new Exception("Operation can not be null");
    } else if (operation.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetLegendGraphic)) {
        log.debug("Never pricing for GetLegendGraphic.");
        return null;
    }/*w w w  .  j a v  a  2s  .c  om*/
    String projection = dw.getOgcrequest().getParameter(OGCConstants.WMS_PARAM_SRS);
    BigDecimal scale = (new BigDecimal(dw.getOgcrequest().calcScale())).setScale(2, BigDecimal.ROUND_HALF_UP);
    int planType = LayerPricing.PAY_PER_REQUEST;
    String service = OGCConstants.WMS_SERVICE_WMS;

    return lc.calculateLayerComplete(spAbbr, layerName, new Date(), projection, scale, new BigDecimal("1"),
            planType, service, operation);
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractConnectorController.java

private List<ProductCharge> getProductCharges(List<CurrencyValue> activeCurrencies, Revision currentRevision) {
    List<ProductCharge> productCharges = new ArrayList<ProductCharge>();
    for (CurrencyValue cv : activeCurrencies) {
        ProductCharge newCharge = new ProductCharge();
        newCharge.setPrice(BigDecimal.ZERO.setScale(
                Integer.parseInt(config.getValue(Names.com_citrix_cpbm_portal_appearance_currency_precision)),
                BigDecimal.ROUND_HALF_UP));
        newCharge.setCurrencyValue(cv);/*from  w w w .j  a  va2s  .  co m*/
        newCharge.setRevision(currentRevision);
        productCharges.add(newCharge);
    }
    return productCharges;
}

From source file:com.osafe.services.OsafePayPalServices.java

public static Map<String, Object> doRefund(DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
        /*            return ServiceUtil.returnError(UtilProperties.getMessage(resource, 
            "AccountingPayPalPaymentGatewayConfigCannotFind", locale));*/
        return ServiceUtil.returnError(
                "Couldn't retrieve a PaymentGatewayConfigPayPal record for Express Checkout, cannot continue.");
    }/* w  w w .  j ava2 s  .  com*/
    GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
    GenericValue captureTrans = PaymentGatewayServices.getCaptureTransaction(orderPaymentPreference);
    BigDecimal refundAmount = (BigDecimal) context.get("refundAmount");
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "RefundTransaction");
    encoder.add("TRANSACTIONID", captureTrans.getString("referenceNum"));
    encoder.add("REFUNDTYPE", "Partial");
    encoder.add("CURRENCYCODE", captureTrans.getString("currencyUomId"));
    encoder.add("AMT", refundAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("NOTE", "Order #" + orderPaymentPreference.getString("orderId"));
    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    if (decoder == null) {
        /*            return ServiceUtil.returnError(UtilProperties.getMessage(resource, 
            "AccountingPayPalUnknownError", locale));*/
        return ServiceUtil.returnError("An unknown error occurred while contacting PayPal");
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
        result.put("refundResult", false);
        result.put("refundRefNum", captureTrans.getString("referenceNum"));
        result.put("refundAmount", BigDecimal.ZERO);
        if (errors.size() == 1) {
            Map.Entry<String, String> error = errors.entrySet().iterator().next();
            result.put("refundCode", error.getKey());
            result.put("refundMessage", error.getValue());
        } else {
            result.put("refundMessage",
                    "Multiple errors occurred, please refer to the gateway response messages");
            result.put("internalRespMsgs", errors);
        }
    } else {
        result.put("refundResult", true);
        result.put("refundAmount", new BigDecimal(decoder.get("GROSSREFUNDAMT")));
        result.put("refundRefNum", decoder.get("REFUNDTRANSACTIONID"));
    }
    return result;
}

From source file:com.dp2345.Setting.java

/**
 * /*from  w  w  w  .j a  v a2 s  .c o m*/
 * 
 * @param amount
 *            
 * @return 
 */
public BigDecimal setScale(BigDecimal amount) {
    if (amount == null) {
        return null;
    }
    int roundingMode;
    if (getPriceRoundType() == RoundType.roundUp) {
        roundingMode = BigDecimal.ROUND_UP;
    } else if (getPriceRoundType() == RoundType.roundDown) {
        roundingMode = BigDecimal.ROUND_DOWN;
    } else {
        roundingMode = BigDecimal.ROUND_HALF_UP;
    }
    return amount.setScale(getPriceScale(), roundingMode);
}

From source file:org.egov.stms.service.es.SewerageIndexService.java

public List<BigDecimal> getGrandTotal(final String ulbName, final List<String> wardList) {
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery().filter(QueryBuilders.matchQuery(ULB_NAME, ulbName));
    boolQuery = boolQuery.filter(QueryBuilders.termsQuery(WARD, wardList));
    final List<BigDecimal> totalValues = new ArrayList<>();

    final SearchRequestBuilder searchRequestBuilder = elasticsearchTemplate.getClient().prepareSearch(SEWERAGE)
            .setQuery(boolQuery).addAggregation(AggregationBuilders.sum(ARREARSSUM).field("arrearAmount"))
            .addAggregation(AggregationBuilders.sum(DEMAND_AMOUNT_SUM).field("demandAmount"))
            .addAggregation(AggregationBuilders.sum(TOTALDEMAND_AMOUNT_SUM).field("totalAmount"))
            .addAggregation(AggregationBuilders.sum(COLLECTED_ARREAR_AMOUNT).field(COLLECTED_ARREAR_AMOUNT))
            .addAggregation(AggregationBuilders.sum(COLLECTED_DEMAND_AMOUNT).field(COLLECTED_DEMAND_AMOUNT))
            .addAggregation(AggregationBuilders.sum(EXTRA_ADVANCE_AMOUNT).field(EXTRA_ADVANCE_AMOUNT));

    final SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
    if (searchResponse != null && searchResponse.getAggregations() != null) {

        final Aggregations collAggr = searchResponse.getAggregations();
        final Sum arresrsaggr = collAggr.get(ARREARSSUM);
        final Sum demanAmountagr = collAggr.get(DEMAND_AMOUNT_SUM);
        final Sum totalDemandaggr = collAggr.get(TOTALDEMAND_AMOUNT_SUM);
        final Sum collectedArrearAmount = collAggr.get(COLLECTED_ARREAR_AMOUNT);
        final Sum collectedDemandAmount = collAggr.get(COLLECTED_DEMAND_AMOUNT);
        final Sum extraAdvanceAmount = collAggr.get(EXTRA_ADVANCE_AMOUNT);

        totalValues.add(BigDecimal.valueOf(arresrsaggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        totalValues.add(BigDecimal.valueOf(demanAmountagr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        totalValues.add(BigDecimal.valueOf(totalDemandaggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        totalValues.add(//  ww w.j a v a  2  s .  c  om
                BigDecimal.valueOf(collectedArrearAmount.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        totalValues.add(
                BigDecimal.valueOf(collectedDemandAmount.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        totalValues.add(BigDecimal.valueOf(collectedArrearAmount.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP).add(BigDecimal.valueOf(collectedDemandAmount.getValue())
                        .setScale(0, BigDecimal.ROUND_HALF_UP)));
        totalValues
                .add(BigDecimal.valueOf(extraAdvanceAmount.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
    }
    return totalValues;

}

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

/**
 * Create a position. The type is given with the properties of the calling
 * command./*  w  w  w  . ja va2  s.co m*/
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return new Return
 * @throws EFapsException on error
 */
public Return createPosition(final Parameter _parameter) throws EFapsException {
    final Instance parent = _parameter.getCallInstance();
    final String amountStr = _parameter.getParameterValue("rateAmount");
    final String account = _parameter.getParameterValue("accountLink");
    final String rateCurrencyLink = _parameter.getParameterValue("rateCurrencyLink");

    final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
    final String typeName = (String) properties.get("Type");
    final Instance curInstance;
    if (parent.getType().isKindOf(CIAccounting.TransactionAbstract.getType())) {
        final PrintQuery print = new PrintQuery(parent);
        final SelectBuilder sel = new SelectBuilder().linkto(CIAccounting.TransactionAbstract.PeriodLink).oid();
        print.addSelect(sel);
        print.execute();
        final Instance periodInst = Instance.get(print.<String>getSelect(sel));
        curInstance = new Period().getCurrency(periodInst).getInstance();
    } else {
        curInstance = new Period().getCurrency(_parameter.getCallInstance()).getInstance();
    }
    BigDecimal amount = DecimalType.parseLocalized(amountStr);
    final Type type = Type.get(typeName);
    if (!type.getUUID().equals(CIAccounting.TransactionPositionCredit.uuid)) {
        amount = amount.negate();
    }
    final Object[] rateObj = new Transaction().getRateObject(_parameter, "", 0);
    final BigDecimal rate = ((BigDecimal) rateObj[0]).divide((BigDecimal) rateObj[1], 12,
            BigDecimal.ROUND_HALF_UP);
    final Insert insert = new Insert(type);
    insert.add(CIAccounting.TransactionPositionAbstract.TransactionLink, parent.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.AccountLink, Instance.get(account).getId());
    insert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curInstance.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, rateCurrencyLink);
    insert.add(CIAccounting.TransactionPositionAbstract.Rate, rateObj);
    insert.add(CIAccounting.TransactionPositionAbstract.Amount,
            amount.divide(rate, 12, BigDecimal.ROUND_HALF_UP));
    insert.add(CIAccounting.TransactionPositionAbstract.RateAmount, amount);
    insert.execute();
    return new Return();
}

From source file:com.selfsoft.business.service.impl.TbFixEntrustServiceImpl.java

public BigDecimal getTotalCostPriceByEntrustList(List<TbFixEntrust> tbfixEntrustList) {
    if (tbfixEntrustList == null || tbfixEntrustList.size() == 0)
        return new BigDecimal("0.00");

    String entrustIds = "";
    for (TbFixEntrust tbFixEntrust : tbfixEntrustList) {
        entrustIds += tbFixEntrust.getId() + ",";
    }/*from  w ww .  ja va2  s. co m*/
    entrustIds = tbfixEntrustList.size() > 0 ? entrustIds.substring(0, entrustIds.length() - 1) : null;

    if (entrustIds != null) {

        StringBuilder sql = new StringBuilder();
        sql.append(
                "select sum(pi.cost_price*m.part_quantity) from tb_fix_entrust fe , tb_maintain_part_content m  , tb_part_info pi");
        sql.append(
                " where fe.id = m.entrust_id and pi.id = m.part_id and m.is_free = 1 and m.is_confirm not in (8000) ");
        sql.append(" and fe.id in ( " + entrustIds + ")");
        sql.append(" union all");
        sql.append(
                " select sum(pi.cost_price*sod.quantity) from tb_fix_entrust fe , tm_stock_out so  , tm_stockout_detail sod , tb_part_info pi");
        sql.append(
                " where fe.entrust_code = so.trust_bill and pi.id = sod.partinfo_id and sod.is_free = 1 and so.id = sod.stockout_id and so.is_confirm not in (8000)");
        sql.append(" and fe.id in ( " + entrustIds + ")");

        List<BigDecimal> objList = tbFixEntrustDao.findByOriginSql(sql.toString(), null);

        BigDecimal wxCostPrice = objList.get(0) != null ? new BigDecimal(objList.get(0).toString())
                : new BigDecimal("0.00");

        BigDecimal xsCostPrice = objList.get(1) != null ? new BigDecimal(objList.get(1).toString())
                : new BigDecimal("0.00");

        BigDecimal result = wxCostPrice.add(xsCostPrice).divide(new BigDecimal("1.00"), 2,
                BigDecimal.ROUND_HALF_UP);

        return result;
    }
    return new BigDecimal("0.00");
}

From source file:com.example.aaron.test.MyGLSurfaceView.java

private static BigDecimal truncateDecimal(float x, int numberofDecimals) {
    if (x > 0) {
        return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_HALF_UP);
    } else {//www. jav a 2 s . c  om
        return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_HALF_DOWN);
    }
}