List of usage examples for java.math RoundingMode HALF_UP
RoundingMode HALF_UP
To view the source code for java.math RoundingMode HALF_UP.
Click Source Link
From source file:org.kuali.ole.select.document.OleVendorCreditMemoDocument.java
@Override public void processAfterRetrieve() { super.processAfterRetrieve(); try {/*from w w w .j a v a 2s.c o m*/ if (this.getVendorAliasName() == null) { populateVendorAliasName(); } Map purchaseOrderTypeIdMap = new HashMap(); if (this.getPurchaseOrderTypeId() != null) { purchaseOrderTypeIdMap.put("purchaseOrderTypeId", this.getPurchaseOrderTypeId()); List<PurchaseOrderType> purchaseOrderTypeDocumentList = (List) getBusinessObjectService() .findMatching(PurchaseOrderType.class, purchaseOrderTypeIdMap); if (purchaseOrderTypeDocumentList != null && purchaseOrderTypeDocumentList.size() > 0) { PurchaseOrderType purchaseOrderTypeDoc = purchaseOrderTypeDocumentList.get(0); this.setOrderType(purchaseOrderTypeDoc); } } List<BigDecimal> newUnitPriceList = new ArrayList<BigDecimal>(); BigDecimal newUnitPrice = new BigDecimal(0); BigDecimal hundred = new BigDecimal(100); List<OleCreditMemoItem> item = this.getItems(); for (int i = 0; item.size() > i; i++) { OleCreditMemoItem items = (OleCreditMemoItem) this.getItem(i); if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) { newUnitPrice = items.getItemUnitPrice().abs(); if (items.getItemUnitPrice() != null && items.getExtendedPrice() != null) { items.setItemSurcharge(items.getExtendedPrice().bigDecimalValue() .subtract(newUnitPrice.multiply(items.getItemQuantity().bigDecimalValue())) .setScale(4, RoundingMode.HALF_UP)); } else { items.setItemSurcharge(BigDecimal.ZERO); } } } if (this.getVendorDetail().getCurrencyType() != null) { if (this.getVendorDetail().getCurrencyType().getCurrencyType() .equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) { currencyTypeIndicator = true; } else { currencyTypeIndicator = false; } } if (this.getVendorDetail() != null && (!currencyTypeIndicator)) { Long currencyTypeId = this.getVendorDetail().getCurrencyType().getCurrencyTypeId(); Map documentNumberMap = new HashMap(); documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId); List<OleExchangeRate> exchangeRateList = (List) getBusinessObjectService().findMatchingOrderBy( OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false); Iterator iterator = exchangeRateList.iterator(); for (OleCreditMemoItem items : item) { iterator = exchangeRateList.iterator(); if (iterator.hasNext()) { OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next(); items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate())); } } } List<OleCreditMemoItem> items = this.getItems(); String itemDescription = ""; for (OleCreditMemoItem singleItem : items) { if (LOG.isDebugEnabled()) { LOG.debug("Title id while retriving ------>" + singleItem.getItemTitleId()); } if (singleItem.getItemTitleId() != null) { /* LOG.debug("###########inside processAfterRetrieve ole credit memo item###########"); HashMap<String, String> queryMap = new HashMap<String, String>(); queryMap.put(OleSelectConstant.DocStoreDetails.ITEMLINKS_KEY, singleItem.getItemTitleId()); List<DocInfoBean> docStoreResult = getBibInfoWrapperService().searchBibInfo(queryMap); Iterator bibIdIterator = docStoreResult.iterator(); if (bibIdIterator.hasNext()) { DocInfoBean docInfoBean = (DocInfoBean) bibIdIterator.next(); if (docInfoBean.getBibIdentifier() == null) { singleItem.setBibUUID(docInfoBean.getUniqueId()); } else { singleItem.setBibUUID(docInfoBean.getBibIdentifier()); } }*/ Bib bib = new BibMarc(); DocstoreClientLocator docstoreClientLocator = new DocstoreClientLocator(); if (singleItem.getItemTitleId() != null && singleItem.getItemTitleId() != "") { bib = docstoreClientLocator.getDocstoreClient().retrieveBib(singleItem.getItemTitleId()); singleItem.setBibUUID(bib.getId()); singleItem .setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(singleItem.getItemTitleId())); } itemDescription = ((bib.getTitle() != null && !bib.getTitle().isEmpty()) ? bib.getTitle() + "," : "") + ((bib.getAuthor() != null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + "," : "") + ((bib.getPublisher() != null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + "," : "") + ((bib.getIsbn() != null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + "," : ""); if (!itemDescription.isEmpty()) { itemDescription = itemDescription.lastIndexOf(",") < 0 ? itemDescription : itemDescription.substring(0, itemDescription.lastIndexOf(",")); } StringEscapeUtils stringEscapeUtils = new StringEscapeUtils(); itemDescription = stringEscapeUtils.unescapeXml(itemDescription); singleItem.setItemDescription(itemDescription); } } if (this.getProrateBy() != null) { this.setProrateQty(this.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)); this.setProrateManual(this.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)); this.setProrateDollar(this.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)); this.setNoProrate(this.getProrateBy().equals(OLEConstants.NO_PRORATE)); } } catch (Exception e) { LOG.error("Exception in OleVendorCreditMemoDocument:processAfterRetrieve " + e); throw new RuntimeException(e); } }
From source file:org.kalypso.model.wspm.tuhh.core.profile.LengthSectionCreator.java
protected static BigDecimal valueToBigDecimal(final Object value) { if (value instanceof BigDecimal) return (BigDecimal) value; if (value instanceof Number) { final double val = ((Number) value).doubleValue(); if (Double.isNaN(val)) return null; return new BigDecimal(val).setScale(IProfileFeature.STATION_SCALE, RoundingMode.HALF_UP); } else/*from w ww . j a va 2 s.c o m*/ return null; }
From source file:com.tibbo.linkserver.plugin.device.file.item.NumericItem.java
private int toInt(Number value) { if (value instanceof Double) { return (new BigDecimal(value.doubleValue())).setScale(0, RoundingMode.HALF_UP).intValue(); }/*from w w w .j a v a 2 s . c om*/ if (value instanceof Float) { return (new BigDecimal(value.floatValue())).setScale(0, RoundingMode.HALF_UP).intValue(); } if (value instanceof BigDecimal) { return ((BigDecimal) value).setScale(0, RoundingMode.HALF_UP).intValue(); } else { return value.intValue(); } }
From source file:org.estatio.dom.lease.invoicing.InvoiceCalculationService.java
/** * Multiplies a value with the range and annual factors * // w w w . java2 s .com * @param rangeFactor * @param annualFactor * @param value * @return */ private BigDecimal calculateValue(final BigDecimal rangeFactor, final BigDecimal annualFactor, final BigDecimal value) { if (value != null && annualFactor != null && rangeFactor != null) { return value.multiply(annualFactor).multiply(rangeFactor).setScale(2, RoundingMode.HALF_UP); } return new BigDecimal("0.00"); }
From source file:org.libreplan.business.orders.daos.OrderElementDAO.java
private BigDecimal average(BigDecimal divisor, BigDecimal sum) { BigDecimal average = new BigDecimal(0); if (sum.compareTo(new BigDecimal(0)) > 0) { average = sum.divide(divisor, new MathContext(2, RoundingMode.HALF_UP)); }//from w ww . j a v a 2 s .c om return average; }
From source file:com.globocom.grou.report.ts.opentsdb.OpenTSDBClient.java
private double formatValue(double value) { try {//from w ww. ja v a2 s .co m return BigDecimal.valueOf(value).round(new MathContext(4, RoundingMode.HALF_UP)).doubleValue(); } catch (NumberFormatException ignore) { return BigDecimal.valueOf(0d).round(new MathContext(4, RoundingMode.HALF_UP)).doubleValue(); } }
From source file:org.rm3l.ddwrt.tiles.status.wan.WANTrafficTile.java
/** * Called when a previously created loader has finished its load. Note * that normally an application is <em>not</em> allowed to commit fragment * transactions while in this call, since it can happen after an * activity's state is saved. See {@link android.support.v4.app.FragmentManager#beginTransaction() * FragmentManager.openTransaction()} for further discussion on this. * <p/>/*from w w w . j av a 2 s . co m*/ * <p>This function is guaranteed to be called prior to the release of * the last data that was supplied for this Loader. At this point * you should remove all use of the old data (since it will be released * soon), but should not do your own release of the data since its Loader * owns it and will take care of that. The Loader will take care of * management of its data so you don't have to. In particular: * <p/> * <ul> * <li> <p>The Loader will monitor for changes to the data, and report * them to you through new calls here. You should not monitor the * data yourself. For example, if the data is a {@link android.database.Cursor} * and you place it in a {@link android.widget.CursorAdapter}, use * the {@link android.widget.CursorAdapter#CursorAdapter(android.content.Context, * android.database.Cursor, int)} constructor <em>without</em> passing * in either {@link android.widget.CursorAdapter#FLAG_AUTO_REQUERY} * or {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER} * (that is, use 0 for the flags argument). This prevents the CursorAdapter * from doing its own observing of the Cursor, which is not needed since * when a change happens you will get a new Cursor throw another call * here. * <li> The Loader will release the data once it knows the application * is no longer using it. For example, if the data is * a {@link android.database.Cursor} from a {@link android.content.CursorLoader}, * you should not call close() on it yourself. If the Cursor is being placed in a * {@link android.widget.CursorAdapter}, you should use the * {@link android.widget.CursorAdapter#swapCursor(android.database.Cursor)} * method so that the old Cursor is not closed. * </ul> * * @param loader The Loader that has finished. * @param data The data generated by the Loader. */ @Override public void onLoadFinished(@NotNull Loader<NVRAMInfo> loader, @Nullable NVRAMInfo data) { //Set tiles Log.d(LOG_TAG, "onLoadFinished: loader=" + loader + " / data=" + data); layout.findViewById(R.id.tile_status_wan_traffic_loading_view).setVisibility(View.GONE); layout.findViewById(R.id.tile_status_wan_traffic_gridLayout).setVisibility(View.VISIBLE); if (data == null) { data = new NVRAMInfo().setException(new DDWRTNoDataException("No Data!")); } @NotNull final TextView errorPlaceHolderView = (TextView) this.layout .findViewById(R.id.tile_status_wan_traffic_error); @Nullable final Exception exception = data.getException(); if (!(exception instanceof DDWRTTileAutoRefreshNotAllowedException)) { if (exception == null) { errorPlaceHolderView.setVisibility(View.GONE); } final String wanIface = data.getProperty(NVRAMInfo.WAN_IFACE); //Iface Name @NotNull final TextView wanIfaceView = (TextView) this.layout.findViewById(R.id.tile_status_wan_traffic_iface); wanIfaceView.setText(Strings.isNullOrEmpty(wanIface) ? "-" : wanIface); @NotNull final TextView wanIngressView = (TextView) this.layout .findViewById(R.id.tile_status_wan_traffic_ingress); String text; final String wanRcvBytes = data.getProperty(wanIface + "_rcv_bytes", "-1"); try { final double wanRcvMBytes = Double.parseDouble(wanRcvBytes) / (1024 * 1024); if (wanRcvMBytes < 0.) { text = "-"; } else { text = Double .toString(new BigDecimal(wanRcvMBytes).setScale(2, RoundingMode.HALF_UP).doubleValue()); } } catch (@NotNull final NumberFormatException nfe) { text = "-"; } wanIngressView.setText(text); @NotNull final TextView wanEgressView = (TextView) this.layout.findViewById(R.id.tile_status_wan_traffic_egress); final String wanXmitBytes = data.getProperty(wanIface + "_xmit_bytes", "-1"); try { final double wanXmitMBytes = Double.parseDouble(wanXmitBytes) / (1024 * 1024); if (wanXmitMBytes < 0.) { text = "-"; } else { text = Double.toString( new BigDecimal(wanXmitMBytes).setScale(2, RoundingMode.HALF_UP).doubleValue()); } } catch (@NotNull final NumberFormatException nfe) { text = "-"; } wanEgressView.setText(text); } if (exception != null && !(exception instanceof DDWRTTileAutoRefreshNotAllowedException)) { //noinspection ThrowableResultOfMethodCallIgnored final Throwable rootCause = Throwables.getRootCause(exception); errorPlaceHolderView.setText("Error: " + (rootCause != null ? rootCause.getMessage() : "null")); final Context parentContext = this.mParentFragmentActivity; errorPlaceHolderView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { //noinspection ThrowableResultOfMethodCallIgnored if (rootCause != null) { Toast.makeText(parentContext, rootCause.getMessage(), Toast.LENGTH_LONG).show(); } } }); errorPlaceHolderView.setVisibility(View.VISIBLE); } doneWithLoaderInstance(this, loader, R.id.tile_status_wan_traffic_togglebutton_title, R.id.tile_status_wan_traffic_togglebutton_separator); Log.d(LOG_TAG, "onLoadFinished(): done loading!"); }
From source file:org.yes.cart.payment.impl.PayPalButtonPaymentGatewayImpl.java
/** * {@inheritDoc}/*from ww w. j a v a 2 s.c o m*/ */ public String getHtmlForm(final String cardHolderName, final String locale, final BigDecimal amount, final String currencyCode, final String orderReference, final Payment payment) { final StringBuilder form = new StringBuilder(); form.append(getHiddenFieldValue("button", "buynow")); form.append(getHiddenFieldValue("cmd", "_cart")); form.append(getHiddenFieldValue("upload", "1")); form.append(getHiddenFieldValue("paymentaction", "sale")); form.append(getHiddenFieldParam("business", PPB_USER)); form.append(getHiddenFieldParam("env", PPB_ENVIRONMENT)); form.append(getHiddenFieldParam("notify_url", PPB_NOTIFYURL)); form.append(getHiddenFieldParam("return", PPB_RETURNURL)); form.append(getHiddenFieldParam("cancel_return", PPB_CANCELURL)); form.append(getHiddenFieldValue("currency_code", currencyCode)); form.append(getHiddenFieldValue("invoice", orderReference)); form.append(getHiddenFieldValue("custom", orderReference)); form.append(getHiddenFieldValue("lc", paymentLocaleTranslator.translateLocale(this, locale))); form.append(getHiddenFieldValue("charset", "UTF-8")); if (payment.getBillingAddress() != null) { form.append(getHiddenFieldValue("first_name", payment.getBillingAddress().getFirstname())); form.append(getHiddenFieldValue("last_name", payment.getBillingAddress().getLastname())); form.append(getHiddenFieldValue("email", payment.getBillingEmail())); } if (payment.getShippingAddress() != null) { form.append(getHiddenFieldValue("address1", payment.getShippingAddress().getAddrline1())); form.append(getHiddenFieldValue("address2", payment.getShippingAddress().getAddrline2())); form.append(getHiddenFieldValue("city", payment.getShippingAddress().getCity())); form.append(getHiddenFieldValue("country", payment.getShippingAddress().getCountryCode())); form.append(getHiddenFieldValue("state", payment.getShippingAddress().getStateCode())); form.append(getHiddenFieldValue("zip", payment.getShippingAddress().getPostcode())); form.append(getHiddenFieldValue("address_override", "1")); } BigDecimal totalItems = Total.ZERO; int i = 1; for (final PaymentLine item : payment.getOrderItems()) { form.append(getHiddenFieldValue("item_name_" + i, item.getSkuName())); form.append(getHiddenFieldValue("item_number_" + i, item.getSkuCode())); // PayPal can only handle whole values, so do ceil final BigDecimal ppQty = item.getQuantity().setScale(0, BigDecimal.ROUND_CEILING); form.append(getHiddenFieldValue("quantity_" + i, ppQty.toPlainString())); final BigDecimal taxUnit = MoneyUtils.isFirstBiggerThanSecond(item.getTaxAmount(), Total.ZERO) ? item.getTaxAmount().divide(item.getQuantity(), Total.ZERO.scale(), RoundingMode.HALF_UP) : Total.ZERO; final BigDecimal itemAmount = item.getUnitPrice().subtract(taxUnit); form.append(getHiddenFieldValue("amount_" + i, itemAmount.toPlainString())); // form.append(getHiddenFieldValue("tax_" + i, taxUnit.setScale(Total.ZERO.scale(), RoundingMode.HALF_UP).toPlainString())); if (ppQty.compareTo(item.getQuantity()) != 0) { // If we have decimals in qty need to save it as item option form.append(getHiddenFieldValue("on0_" + i, "x")); form.append(getHiddenFieldValue("on1_" + i, item.getQuantity().toPlainString())); } i++; totalItems = totalItems.add(itemAmount.multiply(item.getQuantity())); } final BigDecimal payNet = payment.getPaymentAmount().subtract(payment.getTaxAmount()); if (payNet.compareTo(totalItems) < 0) { form.append(getHiddenFieldValue("discount_amount_cart", totalItems.subtract(payNet) .setScale(Total.ZERO.scale(), RoundingMode.HALF_UP).toPlainString())); } form.append(getHiddenFieldValue("tax_cart", payment.getTaxAmount().toPlainString())); return form.toString(); }
From source file:org.openhab.binding.wemo.internal.handler.WemoHandler.java
@Override public void onValueReceived(String variable, String value, String service) { logger.debug("Received pair '{}':'{}' (service '{}') for thing '{}'", new Object[] { variable, value, service, this.getThing().getUID() }); updateStatus(ThingStatus.ONLINE);// ww w. j av a 2 s . c o m this.stateMap.put(variable, value); if (getThing().getThingTypeUID().getId().equals("insight")) { String insightParams = stateMap.get("InsightParams"); if (insightParams != null) { String[] splitInsightParams = insightParams.split("\\|"); if (splitInsightParams[0] != null) { OnOffType binaryState = null; binaryState = splitInsightParams[0].equals("0") ? OnOffType.OFF : OnOffType.ON; if (binaryState != null) { logger.trace("New InsightParam binaryState '{}' for device '{}' received", binaryState, getThing().getUID()); updateState(CHANNEL_STATE, binaryState); } } long lastChangedAt = 0; try { lastChangedAt = Long.parseLong(splitInsightParams[1]) * 1000; // convert s to ms } catch (NumberFormatException e) { logger.error("Unable to parse lastChangedAt value '{}' for device '{}'; expected long", splitInsightParams[1], getThing().getUID()); } ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(lastChangedAt), TimeZone.getDefault().toZoneId()); State lastChangedAtState = new DateTimeType(zoned); if (lastChangedAt != 0) { logger.trace("New InsightParam lastChangedAt '{}' for device '{}' received", lastChangedAtState, getThing().getUID()); updateState(CHANNEL_LASTCHANGEDAT, lastChangedAtState); } State lastOnFor = DecimalType.valueOf(splitInsightParams[2]); if (lastOnFor != null) { logger.trace("New InsightParam lastOnFor '{}' for device '{}' received", lastOnFor, getThing().getUID()); updateState(CHANNEL_LASTONFOR, lastOnFor); } State onToday = DecimalType.valueOf(splitInsightParams[3]); if (onToday != null) { logger.trace("New InsightParam onToday '{}' for device '{}' received", onToday, getThing().getUID()); updateState(CHANNEL_ONTODAY, onToday); } State onTotal = DecimalType.valueOf(splitInsightParams[4]); if (onTotal != null) { logger.trace("New InsightParam onTotal '{}' for device '{}' received", onTotal, getThing().getUID()); updateState(CHANNEL_ONTOTAL, onTotal); } State timespan = DecimalType.valueOf(splitInsightParams[5]); if (timespan != null) { logger.trace("New InsightParam timespan '{}' for device '{}' received", timespan, getThing().getUID()); updateState(CHANNEL_TIMESPAN, timespan); } State averagePower = DecimalType.valueOf(splitInsightParams[6]); // natively given in W if (averagePower != null) { logger.trace("New InsightParam averagePower '{}' for device '{}' received", averagePower, getThing().getUID()); updateState(CHANNEL_AVERAGEPOWER, averagePower); } BigDecimal currentMW = new BigDecimal(splitInsightParams[7]); State currentPower = new DecimalType(currentMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate // mW to W if (currentPower != null) { logger.trace("New InsightParam currentPower '{}' for device '{}' received", currentPower, getThing().getUID()); updateState(CHANNEL_CURRENTPOWER, currentPower); } BigDecimal energyTodayMWMin = new BigDecimal(splitInsightParams[8]); // recalculate mW-mins to Wh State energyToday = new DecimalType( energyTodayMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP)); if (energyToday != null) { logger.trace("New InsightParam energyToday '{}' for device '{}' received", energyToday, getThing().getUID()); updateState(CHANNEL_ENERGYTODAY, energyToday); } BigDecimal energyTotalMWMin = new BigDecimal(splitInsightParams[9]); // recalculate mW-mins to Wh State energyTotal = new DecimalType( energyTotalMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP)); if (energyTotal != null) { logger.trace("New InsightParam energyTotal '{}' for device '{}' received", energyTotal, getThing().getUID()); updateState(CHANNEL_ENERGYTOTAL, energyTotal); } BigDecimal standByLimitMW = new BigDecimal(splitInsightParams[10]); State standByLimit = new DecimalType( standByLimitMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate // mW to W if (standByLimit != null) { logger.trace("New InsightParam standByLimit '{}' for device '{}' received", standByLimit, getThing().getUID()); updateState(CHANNEL_STANDBYLIMIT, standByLimit); } if (currentMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP).intValue() > standByLimitMW .divide(new BigDecimal(1000), RoundingMode.HALF_UP).intValue()) { updateState(CHANNEL_ONSTANDBY, OnOffType.OFF); } else { updateState(CHANNEL_ONSTANDBY, OnOffType.ON); } } } else { State state = stateMap.get("BinaryState").equals("0") ? OnOffType.OFF : OnOffType.ON; logger.debug("State '{}' for device '{}' received", state, getThing().getUID()); if (state != null) { if (getThing().getThingTypeUID().getId().equals("motion")) { updateState(CHANNEL_MOTIONDETECTION, state); if (state.equals(OnOffType.ON)) { State lastMotionDetected = new DateTimeType(); updateState(CHANNEL_LASTMOTIONDETECTED, lastMotionDetected); } } else { updateState(CHANNEL_STATE, state); } } } }
From source file:org.openbravo.erpCommon.utility.CashVATUtil.java
/** * Creates the records into the Cash VAT management table (InvoiceTaxCashVAT), calculating the * percentage paid/collected tax amount and taxable amount. Only for cash vat tax rates * /* w ww .ja v a 2 s . c o m*/ */ public static void createInvoiceTaxCashVAT(final FIN_PaymentDetail paymentDetail, final FIN_PaymentSchedule paymentSchedule, final BigDecimal amount) { try { OBContext.setAdminMode(true); final Invoice invoice = paymentSchedule.getInvoice(); if (invoice != null && invoice.isCashVAT()) { // A previous cash vat line with this payment detail means we are reactivating the payment. // In this case we delete the line final List<InvoiceTaxCashVAT> previousITCashVATs = getInvoiceTaxCashVAT(paymentDetail); if (previousITCashVATs != null && !previousITCashVATs.isEmpty()) { for (InvoiceTaxCashVAT previousITCV : previousITCashVATs) { OBDal.getInstance().remove(previousITCV); } } else { final boolean calculateAmountsBasedOnPercentage; BigDecimal percentage = null; /* Calculate it later on */ final BigDecimal outstandingAmt = invoice.getOutstandingAmount(); if (outstandingAmt.compareTo(amount) == 0) { // We are fully paying the invoice. We need to subtract amounts instead of calculating // them on the fly calculateAmountsBasedOnPercentage = false; } else { // Calculate amounts based on the paid percentage calculateAmountsBasedOnPercentage = true; final boolean isReversal = invoice.getDocumentType().isReversal(); final BigDecimal grandTotalAmt = isReversal ? invoice.getGrandTotalAmount().negate() : invoice.getGrandTotalAmount(); final int currencyPrecission = invoice.getCurrency().getStandardPrecision().intValue(); percentage = amount.multiply(_100).divide(grandTotalAmt, currencyPrecission, RoundingMode.HALF_UP); } for (final InvoiceTax invoiceTax : invoice.getInvoiceTaxList()) { if (invoiceTax.getTax().isCashVAT()) { final InvoiceTaxCashVAT iTCashVAT = OBProvider.getInstance() .get(InvoiceTaxCashVAT.class); iTCashVAT.setOrganization(invoiceTax.getOrganization()); iTCashVAT.setInvoiceTax(invoiceTax); iTCashVAT.setFINPaymentDetail(paymentDetail); final BigDecimal taxAmount; final BigDecimal taxableAmount; if (calculateAmountsBasedOnPercentage) { taxAmount = calculatePercentageAmount(percentage, invoiceTax.getTaxAmount(), invoice.getCurrency()); taxableAmount = calculatePercentageAmount(percentage, invoiceTax.getTaxableAmount(), invoice.getCurrency()); } else { final Map<String, BigDecimal> outstandingAmounts = getTotalOutstandingCashVATAmount( invoiceTax.getId()); percentage = outstandingAmounts.get("percentage"); taxAmount = outstandingAmounts.get("taxAmt"); taxableAmount = outstandingAmounts.get("taxableAmt"); } iTCashVAT.setPercentage(percentage); iTCashVAT.setTaxAmount(taxAmount); iTCashVAT.setTaxableAmount(taxableAmount); invoiceTax.getInvoiceTaxCashVATList().add(iTCashVAT); OBDal.getInstance().save(invoiceTax); OBDal.getInstance().save(iTCashVAT); } } } OBDal.getInstance().flush(); } } finally { OBContext.restorePreviousMode(); } }