Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

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

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

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

Usage

From source file:com.webbfontaine.valuewebb.search.custom.UserCriterion.java

private Criterion getPercentRange() {
    BigDecimal bdValue = new BigDecimal(value.toString());

    BigDecimal range = bdValue.multiply(new BigDecimal(diff).divide(new BigDecimal(100)));

    BigDecimal bdValueFrom = bdValue.subtract(range);
    BigDecimal bdValueTo = bdValue.add(range);
    return Restrictions.and(Restrictions.ge(fullKey, bdValueFrom), Restrictions.le(fullKey, bdValueTo));
}

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

public static Map<String, Object> doExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId"));
    Locale locale = (Locale) context.get("locale");

    GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null);
    GenericValue payPalPaymentMethod = null;
    try {//  w  ww.jav  a  2 s.  c  o  m
        payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod");
        payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod");
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoExpressCheckoutPayment");
    encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    encoder.add("PAYMENTACTION", "Order");
    encoder.add("PAYERID", payPalPaymentMethod.getString("payerId"));
    // set the amount
    encoder.add("AMT", processAmount.setScale(2).toPlainString());
    encoder.add("CURRENCYCODE", orh.getCurrency());
    BigDecimal grandTotal = orh.getOrderGrandTotal();
    BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal subTotal = grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2,
            BigDecimal.ROUND_HALF_UP);
    encoder.add("ITEMAMT", subTotal.toPlainString());
    encoder.add("SHIPPINGAMT", shippingTotal.toPlainString());
    encoder.add("TAXAMT", taxTotal.toPlainString());

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalPaymentSetting, 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 error occurred while communicating with PayPal");
    }

    Map<String, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
        if (errorMessages.containsKey("10417")) {
            // "The transaction cannot complete successfully,  Instruct the customer to use an alternative payment method"
            // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again
            boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
            if (retry) {
                context.put("_RETRY_", false);
                return OsafePayPalServices.doExpressCheckout(dctx, context);
            }
        }
        return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", decoder.get("TRANSACTIONID"));

    Map<String, Object> outMap = null;
    try {
        outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(outMap)) {
        Debug.logError(ServiceUtil.getErrorMessage(outMap), module);
        return outMap;
    }
    return ServiceUtil.returnSuccess();
}

From source file:net.vexelon.myglob.fragments.InvoiceFragment.java

private void updateInvoiceView(User user, List<Map<String, String>> results) {
    if (Defs.LOG_ENABLED)
        Log.v(Defs.LOG_TAG, "Updating invoice for: " + user.getPhoneNumber());

    View v = getView();/*  www .  ja  va2s . c  o  m*/
    boolean found = false;

    for (Map<String, String> map : results) {
        if (map.containsKey(GLBInvoiceXMLParser.TAG_MSISDN)) {
            String value = map.get(GLBInvoiceXMLParser.TAG_MSISDN);
            //            String userPhone = user.getPhoneNumber();
            //            if (value.endsWith(userPhone.substring(userPhone.length() - 6, userPhone.length()))) {
            if (value.trim().length() == 0) {
                // invoice info
                setText(v, R.id.tv_invoice_num, map.get(GLBInvoiceXMLParser.TAG_INVNUM));

                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(Long.parseLong(map.get(GLBInvoiceXMLParser.TAG_DATE)));
                setText(v, R.id.tv_invoice_date, Defs.globalDateFormat.format(calendar.getTime()));
                // costs
                BigDecimal servicesCharge = new BigDecimal("0.00");
                BigDecimal discounts = new BigDecimal("0.00");
                try {
                    // solve discounts amount
                    BigDecimal discount = valOrZero(map.get(GLBInvoiceXMLParser.TAG_DISCOUNT));
                    BigDecimal discountPackage = valOrZero(map.get(GLBInvoiceXMLParser.TAG_DISCOUNT_PACKAGE));
                    BigDecimal discountLoyality = valOrZero(map.get(GLBInvoiceXMLParser.TAG_DISCOUNT_LOYALITY));
                    BigDecimal discountUBB = valOrZero(map.get(GLBInvoiceXMLParser.TAG_DISCOUNT_GLOBUL_UBB));
                    discounts = discounts.add(discount).add(discountPackage).add(discountLoyality)
                            .add(discountUBB);

                    // solve services costs
                    BigDecimal fixedCharge = valOrZero(map.get(GLBInvoiceXMLParser.TAG_FIXED_CHARGE));
                    //                   BigDecimal discounts = new BigDecimal(map.get(GLBInvoiceXMLParser.TAG_DISCOUNT));
                    BigDecimal totalNoVAT = valOrZero(map.get(GLBInvoiceXMLParser.TAG_TOTAL_NO_VAT));
                    servicesCharge = totalNoVAT.subtract(discounts).subtract(fixedCharge);

                } catch (Exception e) {
                    Log.e(Defs.LOG_TAG, "Failed to get decimal prices info!", e);
                    /*
                     * XXX
                     * It would be better to throw exception at this point!
                     */
                    discounts = new BigDecimal(map.get(GLBInvoiceXMLParser.TAG_DISCOUNT));
                }
                setText(v, R.id.tv_invoice_services, servicesCharge.toPlainString());
                setText(v, R.id.tv_invoice_fixed_charge, map.get(GLBInvoiceXMLParser.TAG_FIXED_CHARGE));
                setText(v, R.id.tv_invoice_discount, discounts.toPlainString());
                // totals
                setText(v, R.id.tv_invoice_tot_no_vat, map.get(GLBInvoiceXMLParser.TAG_TOTAL_NO_VAT));
                setText(v, R.id.tv_invoice_vat, map.get(GLBInvoiceXMLParser.TAG_VAT));
                setText(v, R.id.tv_invoice_totvat, map.get(GLBInvoiceXMLParser.TAG_TOTALVAT));
                // amount dues
                setText(v, R.id.tv_invoice_prev_amountdue, map.get(GLBInvoiceXMLParser.TAG_PREV_AMOUNTDUE));
                setText(v, R.id.tv_invoice_paied_amountdue, map.get(GLBInvoiceXMLParser.TAG_PAID_AMOUNTDUE));
                setText(v, R.id.tv_invoice_total_dueamount, map.get(GLBInvoiceXMLParser.TAG_TOTAL_DUEAMOUNT));

                found = true;
                break;
            }
        }
    }

    if (!found) {
        // empty MSISDN was not found!
        setText(v, R.id.tv_invoice_status_nodata, R.string.text_invoice_invalid);
    } else {
        TextView tv = (TextView) v.findViewById(R.id.tv_invoice_status_nodata);
        tv.setVisibility(View.GONE);

        TableLayout table_invoice = (TableLayout) v.findViewById(R.id.table_invoice);
        table_invoice.setVisibility(View.VISIBLE);
    }

    setUpdated(true);
}

From source file:org.egov.ptis.actions.citizen.collection.CollectionAction.java

/**
 * @return//ww  w  .  jav a2s  .  c om
 */
@Action(value = "/collection-generateBill")
public String generateBill() {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Entered method generatePropertyTaxBill, assessment Number: " + assessmentNumber);

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("generatePropertyTaxBill : BasicProperty :" + basicProperty);
    final Map<String, BigDecimal> demandCollMap = propertyTaxUtil
            .getDemandAndCollection(basicProperty.getProperty());
    final BigDecimal currDue = demandCollMap.get(CURR_DMD_STR).subtract(demandCollMap.get(CURR_COLL_STR));
    final BigDecimal arrDue = demandCollMap.get(ARR_DMD_STR).subtract(demandCollMap.get(ARR_COLL_STR));
    /*
     * Advance collection should also be considered for full payment validation. 
     * Current year second installment demand will be the demand for all the advance installments
     */
    BigDecimal advanceCollected = demandCollMap.get(ADVANCE_COLLECTION_STR);
    BigDecimal secondHalfTax = demandCollMap.get(CURR_SECONDHALF_DMD_STR);
    BigDecimal actualAdvanceToBeCollected = secondHalfTax.multiply(new BigDecimal(MAX_ADVANCES_ALLOWED));
    BigDecimal advanceBalance = actualAdvanceToBeCollected.subtract(advanceCollected);

    if (currDue.compareTo(BigDecimal.ZERO) <= 0 && arrDue.compareTo(BigDecimal.ZERO) <= 0
            && advanceBalance.compareTo(BigDecimal.ZERO) <= 0)
        return RESULT_TAXPAID;

    if (OWNERSHIP_TYPE_VAC_LAND
            .equals(basicProperty.getProperty().getPropertyDetail().getPropertyTypeMaster().getCode())) {
        propertyTaxBillable.setVacantLandTaxPayment(Boolean.TRUE);
    }
    propertyTaxBillable.setBasicProperty(basicProperty);
    propertyTaxBillable.setLevyPenalty(true);
    propertyTaxBillable.setReferenceNumber(propertyTaxNumberGenerator
            .generateBillNumber(basicProperty.getPropertyID().getWard().getBoundaryNum().toString()));
    propertyTaxBillable.setBillType(propertyTaxUtil.getBillTypeByCode(BILLTYPE_AUTO));
    try {
        collectXML = URLEncoder.encode(ptBillServiceImpl.getBillXML(propertyTaxBillable), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage());
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.info("Exiting method generatePropertyTaxBill, collectXML: " + collectXML);

    return RESULT_COLLECTTAX;
}

From source file:com.griddynamics.jagger.engine.e1.scenario.DefaultWorkloadSuggestionMaker.java

@Override
public WorkloadConfiguration suggest(BigDecimal desiredTps, NodeTpsStatistics statistics, int maxThreads) {
    log.debug("Going to suggest workload configuration. desired tps {}. statistics {}", desiredTps, statistics);

    Table<Integer, Integer, Pair<Long, BigDecimal>> threadDelayStats = statistics.getThreadDelayStats();

    if (areEqual(desiredTps, BigDecimal.ZERO)) {
        return WorkloadConfiguration.with(0, 0);
    }/*from   w  w w . j a  va 2  s  .com*/

    if (threadDelayStats.isEmpty()) {
        throw new IllegalArgumentException("Cannot suggest workload configuration");
    }

    if (!threadDelayStats.contains(CALIBRATION_CONFIGURATION.getThreads(),
            CALIBRATION_CONFIGURATION.getDelay())) {
        log.debug("Statistics is empty. Going to return calibration info.");
        return CALIBRATION_CONFIGURATION;
    }
    if (threadDelayStats.size() == 2 && areEqual(threadDelayStats.get(1, 0).getSecond(), BigDecimal.ZERO)) {
        log.warn("No calibration info. Going to retry.");
        return CALIBRATION_CONFIGURATION;
    }

    Map<Integer, Pair<Long, BigDecimal>> noDelays = threadDelayStats.column(0);

    log.debug("Calculate next thread count");
    Integer threadCount = findClosestPoint(desiredTps, noDelays);

    if (threadCount == 0) {
        threadCount = 1;
    }

    if (threadCount > maxThreads) {
        log.warn("{} calculated max {} allowed", threadCount, maxThreads);
        threadCount = maxThreads;
    }

    int currentThreads = statistics.getCurrentWorkloadConfiguration().getThreads();
    int diff = threadCount - currentThreads;
    if (diff > maxDiff) {
        log.debug("Increasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        return WorkloadConfiguration.with(currentThreads + maxDiff, 0);
    }

    diff = currentThreads - threadCount;
    if (diff > maxDiff) {
        log.debug("Decreasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        if ((currentThreads - maxDiff) > 1) {
            return WorkloadConfiguration.with(currentThreads - maxDiff, 0);
        } else {
            return WorkloadConfiguration.with(1, 0);
        }
    }

    if (!threadDelayStats.contains(threadCount, 0)) {
        return WorkloadConfiguration.with(threadCount, 0);
    }

    // <delay, <timestamp,tps>>
    Map<Integer, Pair<Long, BigDecimal>> delays = threadDelayStats.row(threadCount);

    // not enough statistics to calculate
    if (delays.size() == 1) {
        int delay = 0;
        BigDecimal tpsFromStat = delays.get(0).getSecond();

        // try to guess
        // tpsFromStat can be zero if no statistics was captured till this time
        if ((tpsFromStat.compareTo(BigDecimal.ZERO) > 0) && (desiredTps.compareTo(BigDecimal.ZERO) > 0)) {

            BigDecimal oneSecond = new BigDecimal(TimeUtils.secondsToMillis(1));
            BigDecimal result = oneSecond.multiply(new BigDecimal(threadCount)).divide(desiredTps, 3,
                    BigDecimal.ROUND_HALF_UP);
            result = result.subtract(oneSecond.multiply(new BigDecimal(threadCount)).divide(tpsFromStat, 3,
                    BigDecimal.ROUND_HALF_UP));

            delay = result.intValue();
        }
        // to have some non zero point in statistics
        if (delay == 0) {
            delay = MIN_DELAY;
        }

        delay = checkDelayInRange(delay);
        return WorkloadConfiguration.with(threadCount, delay);
    }

    log.debug("Calculate next delay");
    Integer delay = findClosestPoint(desiredTps, threadDelayStats.row(threadCount));

    delay = checkDelayInRange(delay);
    return WorkloadConfiguration.with(threadCount, delay);

}

From source file:dk.clanie.money.Money.java

/**
 * Divide evenly into parts.//from  www .  j  a va  2s . c o  m
 * 
 * Divides an amount into parts of approximately the same size while
 * ensuring that the sum of all the parts equals the whole.
 * <p>
 * Parts of unequal size will be distributed evenly in the returned array.
 * <p>
 * For example, if asked to divede 20 into 6 parts the result will be {3.33,
 * 3.34, 3.33, 3.33, 3.34, 3.33}
 * 
 * @param parts -
 *            number of parts
 * @return Money[] with the parts
 */
public Money[] divideEvenlyIntoParts(int parts) {
    Money[] res = new Money[parts];
    final BigDecimal bdParts = new BigDecimal(parts);
    final MathContext mc = MathContext.DECIMAL128;
    BigDecimal sumOfPreviousParts = BigDecimal.ZERO;
    for (int i = 0; i < parts; i++) {
        Money part = new Money();
        BigDecimal sumOfParts = amount.multiply(new BigDecimal(i + 1));
        sumOfParts = sumOfParts.divide(bdParts, mc);
        sumOfParts = sumOfParts.setScale(amount.scale(), mc.getRoundingMode());
        part.amount = sumOfParts.subtract(sumOfPreviousParts);
        sumOfPreviousParts = sumOfParts;
        part.currency = currency;
        res[i] = part;
    }
    return res;
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java

private BigDecimal getQuantity(BigDecimal current, BigDecimal change, boolean credit) {
    return (credit) ? current.add(change) : current.subtract(change);
}

From source file:org.kalypso.kalypsomodel1d2d.conv.results.ResultMeta1d2dHelper.java

public static Date parseTimelineHour(final String hourString, final int year) {
    final BigDecimal hours = NumberUtils.parseQuietDecimal(hourString);
    if (hours == null)
        return null;

    // REMARK: we read the calculation core time with the time zone, as defined in Kalypso Preferences
    final Calendar calendar = Calendar.getInstance(KalypsoCorePlugin.getDefault().getTimeZone());
    calendar.clear();//  w w  w .j av  a  2 s . co  m
    calendar.set(year, 0, 1);

    BigDecimal wholeHours = hours.setScale(0, BigDecimal.ROUND_DOWN);
    final BigDecimal wholeMinutes = hours.subtract(wholeHours).multiply(new BigDecimal("60")); //$NON-NLS-1$
    if (wholeHours.intValue() > 1) {
        wholeHours = new BigDecimal(wholeHours.intValue() - 1);
    }
    calendar.add(Calendar.HOUR, wholeHours.intValue());
    calendar.add(Calendar.MINUTE, wholeMinutes.intValue());

    final boolean lBoolLeapYear = DateUtilities.isLeapYear(calendar);
    if (lBoolLeapYear && calendar.get(Calendar.DAY_OF_YEAR) > 59) {
        calendar.clear();
        calendar.set(year, 0, 1);
        calendar.add(Calendar.HOUR, wholeHours.intValue() - 24);
        calendar.add(Calendar.MINUTE, wholeMinutes.intValue());
    }

    return calendar.getTime();
}

From source file:org.marketcetera.core.position.impl.PositionMetricsCalculatorImpl.java

/**
 * Processes a position close, updating realized P&L and the unrealized cost
 * /*from  w w  w .  j ava  2s .  co m*/
 * @param quantity
 *            the quantity being closed, negative when closing a long position and positive when
 *            closing a short position
 * @param openPrice
 *            the price at which the position was opened
 * @param closePrice
 *            the price at which the position is closing
 */
private void processClose(final BigDecimal quantity, final BigDecimal openPrice, final BigDecimal closePrice) {
    // subtract closePrice from openPrice since quantity has opposite sign
    // more readable may be:
    // quantity.negate().multiply(closePrice.subtract(openPrice))
    mRealizedPL = mRealizedPL.add(quantity.multiply(openPrice.subtract(closePrice)));
    mUnrealizedCost.add(quantity, openPrice);
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdater.java

/**
 * Updates stock quantities when a charge item is saved.
 *
 * @param act the charge item act//  w  ww .j ava 2  s. c  o  m
 * @throws ArchetypeServiceException for any archetype service error
 */
private void updateChargeItem(FinancialAct act) {
    ActBean bean = new ActBean(act, service);
    boolean credit = bean.isA(CustomerAccountArchetypes.CREDIT_ITEM);

    StockQty current = new StockQty(bean);
    StockQty prior = getSavedStockQty(act);
    BigDecimal priorQty = BigDecimal.ZERO;

    if (prior != null && prior.isValid()) {
        priorQty = prior.getQuantity();
        if (!prior.hasProduct(current)) {
            updateStockQuantities(prior, priorQty.negate(), credit);
            priorQty = BigDecimal.ZERO;
        }
    }
    BigDecimal quantity = current.getQuantity();
    if (current.isValid()) {
        if (!MathRules.equals(quantity, priorQty)) {
            BigDecimal diff = quantity.subtract(priorQty);
            updateStockQuantities(current, diff, credit);
        }
    } else {
        bean.removeParticipation(STOCK_LOCATION_PARTICIPATION);
    }
}