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:org.stockwatcher.domain.WatchListItem.java

public double getRateOfReturn() {
    if (startPrice == null || startPrice.equals(ZERO)) {
        throw new IllegalStateException("startPrice is null or zero");
    }/*  w  w  w.j  a  v  a  2  s  . c om*/
    BigDecimal currentPrice = getCurrentPrice();
    if (currentPrice == null || currentPrice.equals(ZERO)) {
        throw new IllegalStateException("currentPrice is null or zero");
    }
    return currentPrice.subtract(startPrice).doubleValue() / startPrice.doubleValue();
}

From source file:org.openbravo.advpaymentmngt.utility.APRM_MatchingUtility.java

/**
 * Split the given bank statement line only when it does not match with the amount of the given
 * transaction. It will create a clone of the given bank statement line with the difference
 * amount. The original bank statement line amounts will be set equal to the amounts in the
 * transaction/*from   ww  w.  ja v  a 2s  .  co  m*/
 * 
 */
private static void splitBankStatementLine(final FIN_Reconciliation reconciliation,
        final FIN_BankStatementLine bankStatementLine, final FIN_FinaccTransaction transaction) {
    try {
        OBContext.setAdminMode(true);
        if (reconciliation == null || bankStatementLine == null || transaction == null) {
            throw new OBException("splitBankStatementLine method requires not null parameters");
        }

        final BigDecimal bslAmount = bankStatementLine.getCramount().subtract(bankStatementLine.getDramount());
        final BigDecimal trxAmount = transaction.getDepositAmount().subtract(transaction.getPaymentAmount());

        // If amounts don't match we continue with the split
        if (bslAmount.compareTo(trxAmount) != 0) {
            if ("Y".equals(reconciliation.getPosted())) {
                // reconciliation posted not possible to split a row
                throw new OBException(OBMessageUtils.messageBD("APRM_SplitBSLReconciliationPosted"));
            }
            if (bankStatementLine.getFinancialAccountTransaction() != null
                    && bankStatementLine.getFinancialAccountTransaction().getReconciliation() != null) {
                throw new OBException(OBMessageUtils.messageBD("APRM_SplitBSLAlreadyMatched"));
            }

            // prevent trigger
            FIN_BankStatement bs = bankStatementLine.getBankStatement();
            bs.setProcessed(false);
            OBDal.getInstance().save(bs);
            OBDal.getInstance().flush();

            // Duplicate bank statement line with pending amount
            FIN_BankStatementLine clonedBSLine = (FIN_BankStatementLine) DalUtil.copy(bankStatementLine, true);
            final BigDecimal credit = bankStatementLine.getCramount().subtract(transaction.getDepositAmount());
            final BigDecimal debit = bankStatementLine.getDramount().subtract(transaction.getPaymentAmount());
            clonedBSLine.setCramount(credit);
            clonedBSLine.setDramount(debit);

            if (credit.compareTo(BigDecimal.ZERO) != 0 && debit.compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal total = credit.subtract(debit);
                if (total.compareTo(BigDecimal.ZERO) == -1) {
                    clonedBSLine.setCramount(BigDecimal.ZERO);
                    clonedBSLine.setDramount(total.abs());
                } else {
                    clonedBSLine.setCramount(total);
                    clonedBSLine.setDramount(BigDecimal.ZERO);
                }
            } else {
                if (credit.compareTo(BigDecimal.ZERO) == -1) {
                    clonedBSLine.setCramount(BigDecimal.ZERO);
                    clonedBSLine.setDramount(credit.abs());
                }
                if (debit.compareTo(BigDecimal.ZERO) == -1) {
                    clonedBSLine.setDramount(BigDecimal.ZERO);
                    clonedBSLine.setCramount(debit.abs());
                }

            }

            // Set bankstatement line amounts with the matched transaction amounts
            bankStatementLine.setCramount(transaction.getDepositAmount());
            bankStatementLine.setDramount(transaction.getPaymentAmount());

            bs.setProcessed(true);

            // Save
            OBDal.getInstance().save(bs);
            OBDal.getInstance().save(clonedBSLine);
            OBDal.getInstance().save(bankStatementLine);
        }

    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.kuali.kpme.tklm.leave.calendar.validation.LeaveCalendarValidationUtil.java

public static List<String> validateLeaveAccrualRuleMaxUsage(LeaveSummaryContract ls, String selectedEarnCode,
        String leaveStartDateString, String leaveEndDateString, BigDecimal leaveAmount,
        LeaveBlock updatedLeaveBlock) {//from  w  ww .j a v a 2 s .com
    List<String> errors = new ArrayList<String>();
    String principalId = HrContext.getTargetPrincipalId();
    long daysSpan = TKUtils.getDaysBetween(TKUtils.formatDateString(leaveStartDateString),
            TKUtils.formatDateString(leaveEndDateString));
    if (leaveAmount == null) {
        leaveAmount = TKUtils.getHoursBetween(TKUtils.formatDateString(leaveStartDateString).toDate().getTime(),
                TKUtils.formatDateString(leaveEndDateString).toDate().getTime());
    }
    if (ls != null && CollectionUtils.isNotEmpty(ls.getLeaveSummaryRows())) {
        BigDecimal oldLeaveAmount = null;
        boolean earnCodeChanged = false;
        if (updatedLeaveBlock != null) {
            if (!updatedLeaveBlock.getEarnCode().equals(selectedEarnCode)) {
                earnCodeChanged = true;
            }
            if (!updatedLeaveBlock.getLeaveAmount().equals(leaveAmount)) {
                oldLeaveAmount = updatedLeaveBlock.getLeaveAmount();
            }
        }
        LocalDate aDate = TKUtils.formatDateString(leaveEndDateString);
        EarnCodeContract earnCodeObj = HrServiceLocator.getEarnCodeService().getEarnCode(selectedEarnCode,
                aDate);
        if (earnCodeObj != null
                && StringUtils.equals(earnCodeObj.getAccrualBalanceAction(),
                        HrConstants.ACCRUAL_BALANCE_ACTION.USAGE)
                || StringUtils.equals(earnCodeObj.getUsageLimit(), "I")) {
            AccrualCategoryContract accrualCategory = HrServiceLocator.getAccrualCategoryService()
                    .getAccrualCategory(earnCodeObj.getAccrualCategory(), aDate);
            if (accrualCategory != null) {
                List<? extends LeaveSummaryRowContract> rows = ls.getLeaveSummaryRows();
                for (LeaveSummaryRowContract aRow : rows) {
                    if (aRow.getAccrualCategory().equals(accrualCategory.getAccrualCategory())) {
                        //Does employee have overrides in place?
                        List<? extends EmployeeOverrideContract> employeeOverrides = LmServiceLocator
                                .getEmployeeOverrideService().getEmployeeOverrides(principalId,
                                        TKUtils.formatDateString(leaveEndDateString));
                        String leavePlan = accrualCategory.getLeavePlan();
                        BigDecimal maxUsage = aRow.getUsageLimit();
                        for (EmployeeOverrideContract eo : employeeOverrides) {
                            if (eo.getLeavePlan().equals(leavePlan)
                                    && eo.getAccrualCategory().equals(aRow.getAccrualCategory())) {
                                if (eo.getOverrideType().equals("MU") && eo.isActive()) {
                                    if (eo.getOverrideValue() != null) {
                                        maxUsage = new BigDecimal(eo.getOverrideValue());
                                    } else { // no limit flag
                                        maxUsage = null;
                                    }
                                }
                            }
                        }
                        BigDecimal ytdUsage = aRow.getYtdApprovedUsage();
                        BigDecimal pendingLeaveBalance = aRow.getPendingLeaveRequests();
                        BigDecimal desiredUsage = new BigDecimal(0);
                        if (pendingLeaveBalance != null) {
                            if (oldLeaveAmount != null) {

                                if (!earnCodeChanged
                                        || StringUtils.equals(updatedLeaveBlock.getAccrualCategory(),
                                                accrualCategory.getAccrualCategory())) {
                                    pendingLeaveBalance = pendingLeaveBalance.subtract(oldLeaveAmount.abs());
                                }
                            }

                            desiredUsage = desiredUsage.add(pendingLeaveBalance);
                        }

                        desiredUsage = desiredUsage.add(leaveAmount.multiply(new BigDecimal(daysSpan + 1)));

                        if (ytdUsage != null) {
                            desiredUsage = desiredUsage.add(ytdUsage);
                        }
                        if (maxUsage != null) {
                            if (desiredUsage.compareTo(maxUsage) > 0) {
                                errors.add("This leave request would exceed the usage limit for "
                                        + aRow.getAccrualCategory()); //errorMessages
                            }
                        }
                    }
                }
            }
        }
    }
    return errors;
}

From source file:org.libreplan.business.planner.entities.SigmoidFunction.java

/**
 * Days with zero hours can occur at the beginning days.
 *
 * To avoid allocating days with zero hours, we iterate through the days and
 * subtract a day from the next day to the current day, until we come up
 * with a day which is no zero/*from  w w w. j av  a2 s. c  o  m*/
 *
 * @param hoursToAllocatePerDay
 */
private void avoidZeroHoursInDays(BigDecimal[] hoursToAllocatePerDay) {
    int length = hoursToAllocatePerDay.length;
    for (int i = 0; i < length; i++) {
        BigDecimal hours = hoursToAllocatePerDay[i];
        if (hours.doubleValue() != 0) {
            return;
        }
        if (i + 1 <= length) {
            BigDecimal next = hoursToAllocatePerDay[i + 1];
            hoursToAllocatePerDay[i + 1] = next.subtract(HOUR_FRAGMENTATION);
            hoursToAllocatePerDay[i] = hours.add(HOUR_FRAGMENTATION);
        }
    }
}

From source file:alfio.model.PriceContainerTest.java

@Test
public void getFinalPriceInputVatNotIncluded() throws Exception {
    generateTestStream(PriceContainer.VatStatus.NOT_INCLUDED).forEach(p -> {
        PriceContainer priceContainer = p.getRight();
        BigDecimal finalPrice = priceContainer.getFinalPrice();
        Integer price = p.getLeft();
        BigDecimal netPrice = MonetaryUtil.centsToUnit(price);
        BigDecimal vatAmount = finalPrice.subtract(netPrice);
        int result = MonetaryUtil.unitToCents(vatAmount
                .subtract(MonetaryUtil.calcVat(netPrice, priceContainer.getVatPercentageOrZero())).abs());
        if (result >= 2) {
            BigDecimal calcVatPerc = vatAmount.divide(finalPrice, 5, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100.00")).setScale(2, RoundingMode.HALF_UP);
            fail(String.format("Expected percentage: %s, got %s, vat %s v. %s", calcVatPerc,
                    priceContainer.getOptionalVatPercentage(), vatAmount,
                    MonetaryUtil.calcVat(netPrice, priceContainer.getVatPercentageOrZero())));
        }//from   www  . ja v a2  s. com
    });
}

From source file:edu.ku.brc.specify.config.LatLonConverter.java

/**
 * Converts BigDecimal to Degrees, Minutes and Decimal Seconds.
 * @param bd the DigDecimal to be converted.
 * @return a 3 piece string//from   ww  w  .jav a2s . c  om
 */
public static String convertToDDMMSS(final BigDecimal bd, final DEGREES_FORMAT degreesFMT,
        final DIRECTION direction, final int decimalLen, final boolean alwaysIncludeDir) {

    if (bd.doubleValue() == 0.0) {
        return "0." + zeroes.substring(0, decimalLen);
    }

    if (useDB) {
        BigDecimal remainder = bd.remainder(one);

        BigDecimal num = bd.subtract(remainder);

        BigDecimal minutes = new BigDecimal(remainder.multiply(sixty).abs().intValue());
        BigDecimal secondsFraction = remainder.abs().multiply(sixty).subtract(minutes);
        BigDecimal seconds = secondsFraction.multiply(sixty);

        //System.out.println("["+decFormatter2.format(num)+"]["+minutes+"]["+seconds+"]");

        return decFormatter2.format(num) + " " + decFormatter2.format(minutes) + " "
                + decFormatter.format(seconds);

    }
    //else

    double num = Math.abs(bd.doubleValue());
    int whole = (int) Math.floor(num);
    double remainder = num - whole;

    double minutes = remainder * 60.0;
    int minutesWhole = (int) Math.floor(minutes);
    double secondsFraction = minutes - minutesWhole;
    double seconds = secondsFraction * 60.0;

    boolean addMinSecsSyms = degreesFMT != DEGREES_FORMAT.None;

    if (minutesWhole == 60) {
        whole += 1;
        minutesWhole = 0;
    }

    // round to 2 decimal places precision
    seconds = Math.round(seconds * 1000) / 1000.0;

    int secondsWhole = (int) Math.floor(seconds);
    if (secondsWhole == 60) {
        minutesWhole += 1;
        seconds = 0.0;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(whole);
    if (degreesFMT == DEGREES_FORMAT.Symbol) {
        sb.append(DEGREES_SYMBOL);
    }
    sb.append(' ');
    sb.append(minutesWhole);
    if (addMinSecsSyms)
        sb.append("'");
    sb.append(' ');

    sb.append(String.format("%2." + decimalLen + "f", seconds));
    if (addMinSecsSyms)
        sb.append("\"");

    if (degreesFMT == DEGREES_FORMAT.String || alwaysIncludeDir) {
        int inx = bd.doubleValue() < 0.0 ? 1 : 0;
        if (direction != DIRECTION.None) {
            sb.append(' ');
            sb.append(direction == DIRECTION.NorthSouth ? northSouth[inx] : eastWest[inx]);
        }
    }
    //System.err.println("["+sb.toString()+"]");
    //return whole + (DEGREES_FORMAT.None ? "\u00B0" : "") + " " + minutesWhole + " " + StringUtils.strip(String.format("%12.10f", new Object[] {seconds}), "0");
    return sb.toString();
}

From source file:nl.strohalm.cyclos.dao.accounts.AccountTypeDAOImpl.java

private BigDecimal doGetBalance(final AccountType accountType, final Collection<MemberGroup> groups,
        final Calendar timePoint) {
    final BigDecimal credits = getSum(accountType, timePoint, groups, true);
    final BigDecimal debits = getSum(accountType, timePoint, groups, false);
    return credits.subtract(debits);
}

From source file:com.willetinc.hadoop.mapreduce.dynamodb.BigDecimalSplitter.java

/**
 * <p>/*  w ww .  j a v a  2s .  c  om*/
 * 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.
 * </p>
 * 
 * <p>
 * So the list [0, 5, 8, 12, 18] would represent splits capturing the
 * intervals:
 * </p>
 * 
 * <p>
 * The smallest positive value supported by DynamoDB 'e' is used to separate
 * intervals
 * </p>
 * 
 * <p>
 * e = 0.0000000000000000000000000000000000001
 * </p>
 * 
 * <p>
 * [0, 5] [5+e, 8] [8+e, 12] [12+e, 18]
 * </p>
 */
List<BigDecimal> split(BigDecimal numSplits, BigDecimal minVal, BigDecimal maxVal) {

    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:es.upm.fiware.rss.settlement.ProductSettlementTask.java

@Override
public void run() {
    this.logger.info("Processing class " + this.model.getProductClass());

    // Aggregate value
    String curr = this.transactions.get(0).getBmCurrency().getTxIso4217Code();
    BigDecimal value = new BigDecimal("0");

    for (DbeTransaction tx : this.transactions) {
        if (tx.getTcTransactionType().equalsIgnoreCase("c")) {
            value = value.add(tx.getFtChargedAmount());
        } else {//from  ww w .  j  av a  2s  .  c o  m
            value = value.subtract(tx.getFtChargedAmount());
        }
    }

    // Calculate RS
    RSSModel sharingRes;
    try {
        AlgorithmFactory factory = new AlgorithmFactory();
        AlgorithmProcessor processor = factory.getAlgorithmProcessor(this.model.getAlgorithmType());

        sharingRes = processor.calculateRevenue(model, value);
        this.settlementManager.generateReport(sharingRes, curr);

    } catch (Exception e) {
        this.logger.info("Error processing transactions of: " + this.model.getAggregatorId() + " "
                + this.model.getOwnerProviderId() + " " + this.model.getProductClass() + " " + e.getMessage());

        // Set transactions as pending
        this.settlementManager.setTxState(transactions, "pending", true);
        return;
    }

    // Set transactions as processed
    this.settlementManager.setTxState(transactions, "processed", true);
}

From source file:org.libreplan.business.planner.entities.SigmoidFunction.java

private BigDecimal[] roundValues(BigDecimal[] allocatedHoursPerDay, BigDecimal truncateValue) {

    BigDecimal[] result = new BigDecimal[allocatedHoursPerDay.length];
    BigDecimal reminder = BigDecimal.ZERO;

    for (int i = 0; i < result.length; i++) {
        BigDecimal value = allocatedHoursPerDay[i];
        value = value.add(reminder);//from   w  w w.ja  va2  s . c o m

        BigDecimal intPart = intPart(value);
        BigDecimal decimalPart = decimalPart(value);
        reminder = calculateReminder(decimalPart, truncateValue);
        decimalPart = decimalPart.subtract(reminder);
        result[i] = intPart.add(decimalPart);
    }
    return result;
}