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:nl.strohalm.cyclos.entities.accounts.loans.LoanParameters.java

/**
 * Calculates the monthly interests for the given parameters
 * @return 0 if no monthly interests, or the applied interests otherwise (ie: if monthly interests = 1%, paymentCount = 1 and delay = 0, returns
 * 10 for amount = 1000)//from   ww w.  j av a  2  s  .c o m
 */
public BigDecimal calculateMonthlyInterests(final BigDecimal amount, final int paymentCount, Calendar grantDate,
        Calendar firstExpirationDate, final MathContext mathContext) {
    if (monthlyInterest == null || amount.compareTo(BigDecimal.ZERO) != 1 || paymentCount < 1) {
        return BigDecimal.ZERO;
    }
    // Calculate the delay
    final Calendar now = Calendar.getInstance();
    grantDate = grantDate == null ? now : grantDate;
    firstExpirationDate = firstExpirationDate == null ? (Calendar) now.clone() : firstExpirationDate;
    final Calendar shouldBeFirstExpiration = (Calendar) grantDate.clone();
    shouldBeFirstExpiration.add(Calendar.MONTH, 1);
    int delay = DateHelper.daysBetween(shouldBeFirstExpiration, firstExpirationDate);
    if (delay < 0) {
        delay = 0;
    }

    final BigDecimal grantFee = calculateGrantFee(amount);
    final BigDecimal baseAmount = amount.add(grantFee);
    final BigDecimal interests = monthlyInterest.divide(new BigDecimal(100), mathContext);
    final BigDecimal numerator = new BigDecimal(
            Math.pow(1 + interests.doubleValue(), paymentCount + delay / 30F)).multiply(interests);
    final BigDecimal denominator = new BigDecimal(Math.pow(1 + interests.doubleValue(), paymentCount) - 1);
    final BigDecimal paymentAmount = baseAmount.multiply(numerator).divide(denominator, mathContext);
    final BigDecimal totalAmount = paymentAmount.multiply(new BigDecimal(paymentCount));
    return totalAmount.subtract(baseAmount);
}

From source file:co.nubetech.apache.hadoop.BigDecimalSplitter.java

/**
 * Returns a list of BigDecimals one element longer than the list of input
 * splits. This represents the boundaries between input splits. All splits
 * are open on the top end, except the last one.
 * /*from   www.  ja  v a2  s .c om*/
 * So the list [0, 5, 8, 12, 18] would represent splits capturing the
 * intervals:
 * 
 * [0, 5) [5, 8) [8, 12) [12, 18] note the closed interval for the last
 * split.
 */
List<BigDecimal> split(BigDecimal numSplits, BigDecimal minVal, BigDecimal maxVal) throws SQLException {

    List<BigDecimal> splits = new ArrayList<BigDecimal>();

    // Use numSplits as a hint. May need an extra task if the size doesn't
    // divide cleanly.

    BigDecimal splitSize = tryDivide(maxVal.subtract(minVal), (numSplits));
    if (splitSize.compareTo(MIN_INCREMENT) < 0) {
        splitSize = MIN_INCREMENT;
        LOG.warn("Set BigDecimal splitSize to MIN_INCREMENT");
    }

    BigDecimal curVal = minVal;

    while (curVal.compareTo(maxVal) <= 0) {
        splits.add(curVal);
        curVal = curVal.add(splitSize);
    }

    if (splits.get(splits.size() - 1).compareTo(maxVal) != 0 || splits.size() == 1) {
        // We didn't end on the maxVal. Add that to the end of the list.
        splits.add(maxVal);
    }

    return splits;
}

From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java

public KmerRangePartition[] getEqualAreaPartitions() {
    KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions];

    // calc 4^kmerSize
    BigInteger kmerend = BigInteger.valueOf(4).pow(this.kmerSize);
    BigDecimal bdkmerend = new BigDecimal(kmerend);
    // moves between x (0~1) y (0~1)
    // sum of area (0.5)
    double kmerArea = 0.5;
    double sliceArea = kmerArea / this.numPartitions;

    // we think triangle is horizontally flipped so calc get easier.
    double x1 = 0;

    List<BigInteger> widths = new ArrayList<BigInteger>();
    BigInteger widthSum = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        // x2*x2 = 2*sliceArea + x1*x1
        double temp = (2 * sliceArea) + (x1 * x1);
        double x2 = Math.sqrt(temp);

        BigDecimal bdx1 = BigDecimal.valueOf(x1);
        BigDecimal bdx2 = BigDecimal.valueOf(x2);

        // if i increases, bdw will be decreased
        BigDecimal bdw = bdx2.subtract(bdx1);

        BigInteger bw = bdw.multiply(bdkmerend).toBigInteger();
        if (bw.compareTo(BigInteger.ZERO) <= 0) {
            bw = BigInteger.ONE;// w ww. jav a2 s .  c  om
        }

        if (widthSum.add(bw).compareTo(kmerend) > 0) {
            bw = kmerend.subtract(widthSum);
        }

        if (i == this.numPartitions - 1) {
            // last case
            if (widthSum.add(bw).compareTo(kmerend) < 0) {
                bw = kmerend.subtract(widthSum);
            }
        }

        // save it
        widths.add(bw);
        widthSum = widthSum.add(bw);

        x1 = x2;
    }

    BigInteger cur_begin = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        BigInteger slice_width = widths.get(this.numPartitions - 1 - i);

        BigInteger slice_begin = cur_begin;

        if (slice_begin.add(slice_width).compareTo(kmerend) > 0) {
            slice_width = kmerend.subtract(slice_begin);
        }

        BigInteger slice_end = cur_begin.add(slice_width).subtract(BigInteger.ONE);

        KmerRangePartition slice = new KmerRangePartition(this.kmerSize, this.numPartitions, i, slice_width,
                slice_begin, slice_end);
        partitions[i] = slice;

        cur_begin = cur_begin.add(slice_width);
    }

    return partitions;
}

From source file:org.apache.sqoop.mapreduce.db.BigDecimalSplitter.java

/**
 * Returns a list of BigDecimals one element longer than the list of input
 * splits.  This represents the boundaries between input splits.  All splits
 * are open on the top end, except the last one.
 *
 * So the list [0, 5, 8, 12, 18] would represent splits capturing the
 * intervals://from   w w  w . jav  a2 s  .c  o  m
 *
 * [0, 5)
 * [5, 8)
 * [8, 12)
 * [12, 18] note the closed interval for the last split.
 */
protected List<BigDecimal> split(BigDecimal numSplits, BigDecimal minVal, BigDecimal maxVal)
        throws SQLException {

    List<BigDecimal> splits = new ArrayList<BigDecimal>();

    // Use numSplits as a hint. May need an extra task if the size doesn't
    // divide cleanly.

    BigDecimal splitSize = tryDivide(maxVal.subtract(minVal), (numSplits));
    if (splitSize.compareTo(MIN_INCREMENT) < 0) {
        splitSize = MIN_INCREMENT;
        LOG.warn("Set BigDecimal splitSize to MIN_INCREMENT");
    }

    BigDecimal curVal = minVal;

    while (curVal.compareTo(maxVal) <= 0) {
        splits.add(curVal);
        curVal = curVal.add(splitSize);
    }

    if (splits.get(splits.size() - 1).compareTo(maxVal) != 0 || splits.size() == 1) {
        // We didn't end on the maxVal. Add that to the end of the list.
        splits.add(maxVal);
    }

    return splits;
}

From source file:org.openconcerto.erp.graph.GraphArticleMargePanel.java

@Override
protected void updateDataset(List<String> labels, List<Number> values) {

    final SQLTable tableVFElement = Configuration.getInstance().getDirectory()
            .getElement("SAISIE_VENTE_FACTURE_ELEMENT").getTable();

    final SQLSelect sel = new SQLSelect(tableVFElement.getBase());
    final String field = "NOM";

    sel.addSelect(tableVFElement.getField(field));

    sel.addSelect(tableVFElement.getField("PA_HT"));
    sel.addSelect(tableVFElement.getField("PV_HT"));
    sel.addSelect(tableVFElement.getField("QTE"), "SUM");

    final List<Object[]> rowsArticle = (List<Object[]>) Configuration.getInstance().getBase().getDataSource()
            .execute(sel.asString() + " GROUP BY \"SAISIE_VENTE_FACTURE_ELEMENT\".\"" + field + "\""
                    + ",\"SAISIE_VENTE_FACTURE_ELEMENT\".\"PA_HT\""
                    + ",\"SAISIE_VENTE_FACTURE_ELEMENT\".\"PV_HT\"", new ArrayListHandler());

    Collections.sort(rowsArticle, new Comparator<Object[]>() {
        @Override/*  ww  w .  j a v  a 2  s.  c o m*/
        public int compare(Object[] o1, Object[] o2) {

            BigDecimal pa1 = (BigDecimal) o1[1];
            BigDecimal pv1 = (BigDecimal) o1[2];
            BigDecimal qte1 = new BigDecimal(o1[3].toString());

            BigDecimal pa2 = (BigDecimal) o2[1];
            BigDecimal pv2 = (BigDecimal) o2[2];
            BigDecimal qte2 = new BigDecimal(o2[3].toString());

            BigDecimal marge1 = pv1.subtract(pa1).multiply(qte1, MathContext.DECIMAL128);
            BigDecimal marge2 = pv2.subtract(pa2).multiply(qte2, MathContext.DECIMAL128);
            return marge1.compareTo(marge2);
        }
    });

    for (int i = 0; i < 10 && i < rowsArticle.size(); i++) {
        Object[] o = rowsArticle.get(i);
        BigDecimal pa2 = (BigDecimal) o[1];
        BigDecimal pv2 = (BigDecimal) o[2];
        BigDecimal qte2 = new BigDecimal(o[3].toString());
        BigDecimal marge2 = pv2.subtract(pa2).multiply(qte2, MathContext.DECIMAL128);

        final String string = o[0].toString();
        values.add(marge2);
        labels.add(string);
    }

}

From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.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 {/*from www .  j a  v  a2  s . c  om*/
        payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod", false);
        payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod", false);
    } 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));
    }

    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 PayPalServices.doExpressCheckout(dctx, context);
            }
        }
        return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    Map<String, Object> inMap = new HashMap<String, Object>();
    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:org.ofbiz.accounting.thirdparty.paypal.PayPalServices.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  w  w.j  a  v a  2  s.c om
        payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod", false);
        payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod", false);
    } 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));
    }

    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 PayPalServices.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:org.archfirst.bfoms.spec.accounts.BaseAccountsTest.java

public void setUpBrokerageAccount(String accountName, BigDecimal cashPosition) {

    createBrokerageAccount(accountName);

    // Adjust cash position
    BigDecimal currentCashPosition = getCashPosition(accountName).getAmount();
    if (currentCashPosition != cashPosition) {
        transferCash(EXTERNAL_ACCOUNT_NAME1, accountName, cashPosition.subtract(currentCashPosition));
    }/*from w w  w  .j  ava  2  s  . co  m*/
}

From source file:org.openhab.ui.classic.internal.render.SetpointRenderer.java

@Override
public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException {
    Setpoint sp = (Setpoint) w;/* w ww.  j  a v  a2 s  .c o m*/

    State state = itemUIRegistry.getState(w);
    String newLowerState = state.toString();
    String newHigherState = state.toString();

    // set defaults for min, max and step
    BigDecimal step = sp.getStep();
    if (step == null) {
        step = BigDecimal.ONE;
    }
    BigDecimal minValue = sp.getMinValue();
    if (minValue == null) {
        minValue = BigDecimal.ZERO;
    }
    BigDecimal maxValue = sp.getMaxValue();
    if (maxValue == null) {
        maxValue = BigDecimal.valueOf(100);
    }

    // if the current state is a valid value, we calculate the up and down step values
    if (state instanceof DecimalType || state instanceof QuantityType) {
        BigDecimal currentState;
        if (state instanceof DecimalType) {
            currentState = ((DecimalType) state).toBigDecimal();
        } else {
            currentState = ((QuantityType<?>) state).toBigDecimal();
        }
        BigDecimal newLower = currentState.subtract(step);
        BigDecimal newHigher = currentState.add(step);
        if (newLower.compareTo(minValue) < 0) {
            newLower = minValue;
        }
        if (newHigher.compareTo(maxValue) > 0) {
            newHigher = maxValue;
        }
        newLowerState = newLower.toString();
        newHigherState = newHigher.toString();

        if (state instanceof QuantityType) {
            newLowerState = newLowerState + " " + ((QuantityType<?>) state).getUnit().toString();
            newHigherState = newHigherState + " " + ((QuantityType<?>) state).getUnit().toString();
        }
    }

    String snippetName = "setpoint";
    String snippet = getSnippet(snippetName);

    snippet = StringUtils.replace(snippet, "%id%", itemUIRegistry.getWidgetId(w));
    snippet = StringUtils.replace(snippet, "%category%", getCategory(w));
    snippet = StringUtils.replace(snippet, "%item%", w.getItem());
    snippet = StringUtils.replace(snippet, "%state%", getState(w));
    snippet = StringUtils.replace(snippet, "%newlowerstate%", newLowerState);
    snippet = StringUtils.replace(snippet, "%newhigherstate%", newHigherState);
    snippet = StringUtils.replace(snippet, "%label%", getLabel(w));
    snippet = StringUtils.replace(snippet, "%state%", getState(w));
    snippet = StringUtils.replace(snippet, "%format%", getFormat());
    snippet = StringUtils.replace(snippet, "%servletname%", WebAppServlet.SERVLET_NAME);
    snippet = StringUtils.replace(snippet, "%minValue%", minValue.toString());
    snippet = StringUtils.replace(snippet, "%maxValue%", maxValue.toString());
    snippet = StringUtils.replace(snippet, "%step%", step.toString());

    // Process the color tags
    snippet = processColor(w, snippet);

    sb.append(snippet);
    return null;
}

From source file:org.archfirst.bfoms.spec.accounts.BaseAccountsTest.java

public void setUpBrokerageAccount(String accountName, String symbol, BigDecimal position) {

    createBrokerageAccount(accountName);

    // Adjust securities position
    BigDecimal currentPosition = getSecuritiesPosition(accountName, symbol);
    if (currentPosition != position) {
        transferSecurities(EXTERNAL_ACCOUNT_NAME1, accountName, symbol, position.subtract(currentPosition));
    }//from   w w  w  .jav  a2  s.c o m
}