Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java

private void verify(final TransferDTO params) {

    if (params.getFrom() != null) {
        final Account from = fetchService.fetch(params.getFrom(), MemberAccount.Relationships.MEMBER);
        params.setFromOwner(from.getOwner());
    }/*from   ww w  . jav a2  s .c  o m*/
    if (params.getTo() != null) {
        final Account to = fetchService.fetch(params.getTo(), MemberAccount.Relationships.MEMBER);
        params.setToOwner(to.getOwner());
    }

    validate(params);

    final AccountOwner fromOwner = params.getFromOwner();
    final AccountOwner toOwner = params.getToOwner();

    // Validate the transfer type
    final TransferType transferType = validateTransferType(params);

    // Retrieve the from and to accounts
    final Account fromAccount = accountService.getAccount(new AccountDTO(fromOwner, transferType.getFrom()));
    final Account toAccount = accountService.getAccount(new AccountDTO(toOwner, transferType.getTo()));

    if (fromAccount.equals(toAccount)) {
        throw new ValidationException(new ValidationError("payment.error.sameAccount"));
    }

    // Retrieve the amount
    final BigDecimal amount = params.getAmount();

    // Check the minimum payment
    if (amount.compareTo(getMinimumPayment()) == -1) {
        final LocalSettings localSettings = settingsService.getLocalSettings();

        throw new TransferMinimumPaymentException(
                localSettings.getUnitsConverter(fromAccount.getType().getCurrency().getPattern())
                        .toString(getMinimumPayment()),
                fromAccount, amount);
    }

    // Update some retrieved parameters on the DTO
    params.setTransferType(transferType);
    params.setFrom(fromAccount);
    params.setTo(toAccount);
    if (StringUtils.isBlank(params.getDescription())) {
        params.setDescription(transferType.getDescription());
    }
}

From source file:com.gst.portfolio.loanproduct.serialization.LoanProductDataValidator.java

public void validateMinMaxConstraints(final JsonElement element, final DataValidatorBuilder baseDataValidator,
        final LoanProduct loanProduct, Integer cycleNumber) {

    final Map<String, BigDecimal> minmaxValues = loanProduct
            .fetchBorrowerCycleVariationsForCycleNumber(cycleNumber);
    final String principalParameterName = "principal";
    BigDecimal principalAmount = null;
    BigDecimal minPrincipalAmount = null;
    BigDecimal maxPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(principalParameterName, element)) {
        principalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName,
                element);/*w w w .j ava  2 s  .  co m*/
        minPrincipalAmount = minmaxValues.get(LoanProductConstants.minPrincipal);
        maxPrincipalAmount = minmaxValues.get(LoanProductConstants.maxPrincipal);
    }

    if ((minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)
            && (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)) {
        baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
                .inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount);
    } else {
        if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
            baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
                    .notLessThanMin(minPrincipalAmount);
        } else if (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
            baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
                    .notGreaterThanMax(maxPrincipalAmount);
        }
    }

    final String numberOfRepaymentsParameterName = "numberOfRepayments";
    Integer maxNumberOfRepayments = null;
    Integer minNumberOfRepayments = null;
    Integer numberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) {
        numberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element);
        if (minmaxValues.get(LoanProductConstants.minNumberOfRepayments) != null) {
            minNumberOfRepayments = minmaxValues.get(LoanProductConstants.minNumberOfRepayments)
                    .intValueExact();
        }
        if (minmaxValues.get(LoanProductConstants.maxNumberOfRepayments) != null) {
            maxNumberOfRepayments = minmaxValues.get(LoanProductConstants.maxNumberOfRepayments)
                    .intValueExact();
        }
    }

    if (maxNumberOfRepayments != null && maxNumberOfRepayments.compareTo(0) == 1) {
        if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
            baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
                    .inMinMaxRange(minNumberOfRepayments, maxNumberOfRepayments);
        } else {
            baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
                    .notGreaterThanMax(maxNumberOfRepayments);
        }
    } else if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
        baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
                .notLessThanMin(minNumberOfRepayments);
    }

    final String interestRatePerPeriodParameterName = "interestRatePerPeriod";
    BigDecimal interestRatePerPeriod = null;
    BigDecimal minInterestRatePerPeriod = null;
    BigDecimal maxInterestRatePerPeriod = null;
    if (this.fromApiJsonHelper.parameterExists(interestRatePerPeriodParameterName, element)) {
        interestRatePerPeriod = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, element);
        minInterestRatePerPeriod = minmaxValues.get(LoanProductConstants.minInterestRatePerPeriod);
        maxInterestRatePerPeriod = minmaxValues.get(LoanProductConstants.maxInterestRatePerPeriod);
    }
    if (maxInterestRatePerPeriod != null) {
        if (minInterestRatePerPeriod != null) {
            baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
                    .inMinAndMaxAmountRange(minInterestRatePerPeriod, maxInterestRatePerPeriod);
        } else {
            baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
                    .notGreaterThanMax(maxInterestRatePerPeriod);
        }
    } else if (minInterestRatePerPeriod != null) {
        baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
                .notLessThanMin(minInterestRatePerPeriod);
    }

}

From source file:com.gst.accounting.journalentry.service.AccountingProcessorHelper.java

public void revertCashBasedJournalEntryForSharesCharges(final Office office, final String currencyCode,
        final CASH_ACCOUNTS_FOR_SHARES accountTypeToBeCredited, final Long shareProductId,
        final Long shareAccountId, final String transactionId, final Date transactionDate,
        final BigDecimal totalAmount, final List<ChargePaymentDTO> chargePaymentDTOs) {
    final Map<GLAccount, BigDecimal> creditDetailsMap = new LinkedHashMap<>();
    for (final ChargePaymentDTO chargePaymentDTO : chargePaymentDTOs) {
        final GLAccount chargeSpecificAccount = getLinkedGLAccountForShareCharges(shareProductId,
                accountTypeToBeCredited.getValue(), chargePaymentDTO.getChargeId());
        BigDecimal chargeSpecificAmount = chargePaymentDTO.getAmount();

        // adjust net credit amount if the account is already present in the
        // map//from  ww w  .j a va 2s.  co m
        if (creditDetailsMap.containsKey(chargeSpecificAccount)) {
            final BigDecimal existingAmount = creditDetailsMap.get(chargeSpecificAccount);
            chargeSpecificAmount = chargeSpecificAmount.add(existingAmount);
        }
        creditDetailsMap.put(chargeSpecificAccount, chargeSpecificAmount);
    }

    BigDecimal totalCreditedAmount = BigDecimal.ZERO;
    for (final Map.Entry<GLAccount, BigDecimal> entry : creditDetailsMap.entrySet()) {
        final GLAccount account = entry.getKey();
        final BigDecimal amount = entry.getValue();
        totalCreditedAmount = totalCreditedAmount.add(amount);
        createDebitJournalEntryForShares(office, currencyCode, account, shareAccountId, transactionId,
                transactionDate, amount);
    }
    if (totalAmount.compareTo(totalCreditedAmount) != 0) {
        throw new PlatformDataIntegrityException(
                "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code",
                "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code");
    }
}

From source file:com.gst.accounting.journalentry.service.AccountingProcessorHelper.java

public void createCashBasedJournalEntryForSharesCharges(final Office office, final String currencyCode,
        final CASH_ACCOUNTS_FOR_SHARES accountTypeToBeCredited, final Long shareProductId,
        final Long shareAccountId, final String transactionId, final Date transactionDate,
        final BigDecimal totalAmount, final List<ChargePaymentDTO> chargePaymentDTOs) {
    final Map<GLAccount, BigDecimal> creditDetailsMap = new LinkedHashMap<>();
    for (final ChargePaymentDTO chargePaymentDTO : chargePaymentDTOs) {
        final GLAccount chargeSpecificAccount = getLinkedGLAccountForShareCharges(shareProductId,
                accountTypeToBeCredited.getValue(), chargePaymentDTO.getChargeId());
        BigDecimal chargeSpecificAmount = chargePaymentDTO.getAmount();

        // adjust net credit amount if the account is already present in the
        // map/* w  w  w  .j  a v a  2 s .  co m*/
        if (creditDetailsMap.containsKey(chargeSpecificAccount)) {
            final BigDecimal existingAmount = creditDetailsMap.get(chargeSpecificAccount);
            chargeSpecificAmount = chargeSpecificAmount.add(existingAmount);
        }
        creditDetailsMap.put(chargeSpecificAccount, chargeSpecificAmount);
    }

    BigDecimal totalCreditedAmount = BigDecimal.ZERO;
    for (final Map.Entry<GLAccount, BigDecimal> entry : creditDetailsMap.entrySet()) {
        final GLAccount account = entry.getKey();
        final BigDecimal amount = entry.getValue();
        totalCreditedAmount = totalCreditedAmount.add(amount);
        createCreditJournalEntryForShares(office, currencyCode, account, shareAccountId, transactionId,
                transactionDate, amount);
    }
    if (totalAmount.compareTo(totalCreditedAmount) != 0) {
        throw new PlatformDataIntegrityException(
                "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code",
                "Recent Portfolio changes w.r.t Charges for shares have Broken the accounting code");
    }
}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * /*from ww  w  . j  av a 2 s.c  om*/
 *
 * @param motheds
 * @param fe
 * @param num
 * @param weight
 * @return BigDecimal
 */
public BigDecimal computeFreight(String motheds, FreightExpress fe, Integer num, BigDecimal weight) {
    BigDecimal price = new BigDecimal(0);
    if (num == 0) {
        return price;
    }
    // 
    if ("0".equals(motheds)) {
        // ?
        if (num < Integer.parseInt(fe.getExpressStart().toString())) {
            //  =  +   -*
            int a = 0;
            BigDecimal temp = fe.getExpressPostageplus().multiply(new BigDecimal(a));
            price = fe.getExpressPostage().add(temp);
        } else {
            //  =  +   -*
            int a = num - Integer.parseInt(fe.getExpressStart().toString());
            BigDecimal temp = fe.getExpressPostageplus().multiply(
                    (new BigDecimal(a)).divide(new BigDecimal(fe.getExpressPlusN1()), 0, BigDecimal.ROUND_UP));
            price = fe.getExpressPostage().add(temp);
        }

        return price;
    } else {
        // ??
        if (weight.compareTo(new BigDecimal(fe.getExpressStart())) == -1) {
            // ? = ? + ?-?*?
            BigDecimal a = new BigDecimal(0);
            BigDecimal temp = fe.getExpressPostageplus().multiply(a);
            price = fe.getExpressPostage().add(temp);
        } else {
            // ? = ? + ?-?*?
            BigDecimal a = weight.subtract(new BigDecimal(fe.getExpressStart()));
            BigDecimal temp = fe.getExpressPostageplus()
                    .multiply(a.divide(new BigDecimal(fe.getExpressPlusN1()), 0, BigDecimal.ROUND_UP));
            price = fe.getExpressPostage().add(temp);
        }

        return price;
    }
}

From source file:net.sourceforge.fenixedu.domain.ExecutionCourse.java

public void setUnitCreditValue(BigDecimal unitCreditValue, String justification) {
    if (unitCreditValue != null && (unitCreditValue.compareTo(BigDecimal.ZERO) < 0
            || unitCreditValue.compareTo(BigDecimal.ONE) > 0)) {
        throw new DomainException("error.executionCourse.unitCreditValue.range");
    }/*from ww  w .  j  a  v a2s. co m*/
    if (unitCreditValue != null && unitCreditValue.compareTo(BigDecimal.ZERO) != 0 && getEffortRate() == null) {
        throw new DomainException("error.executionCourse.unitCreditValue.noEffortRate");
    }
    if (getEffortRate() != null && (unitCreditValue != null
            && unitCreditValue.compareTo(BigDecimal.valueOf(Math.min(getEffortRate().doubleValue(), 1.0))) < 0
            && StringUtils.isBlank(justification))) {
        throw new DomainException(
                "error.executionCourse.unitCreditValue.lower.effortRate.withoutJustification");
    }
    super.setUnitCreditValueNotes(justification);
    super.setUnitCreditValue(unitCreditValue);
}

From source file:com.nkapps.billing.dao.PaymentDaoImpl.java

@Override
public void saveKeyPaymentAndTransaction(BigDecimal keyTransactionId, BigDecimal keyCost) throws Exception {
    Session session = getSession();//from  w w  w  .  j av  a  2 s. c om
    Transaction transaction = session.beginTransaction();

    LocalDateTime dateTime = LocalDateTime.now();

    KeyTransaction ktr = (KeyTransaction) session.get(KeyTransaction.class, keyTransactionId);
    String q = " SELECT p.id AS id, p.tin AS tin, p.paymentNum AS paymentNum, p.paymentDate AS paymentDate,"
            + "  p.paymentSum AS paymentSum, p.sourceCode AS sourceCode,"
            + " p.state AS state, p.tinDebtor as tinDebtor,p.claim as claim, p.issuerSerialNumber as issuerSerialNumber,"
            + " p.issuerIp as issuerIp,p.dateCreated AS dateCreated, p.dateUpdated as dateUpdated, "
            + " p.paymentSum - COALESCE((SELECT SUM(paidSum) FROM KeyPayment kp WHERE kp.payment = p),0) AS overSum "
            + " FROM Payment p " + " WHERE p.tin = :tin AND p.state IN (1,2) AND p.claim = 0"
            + " ORDER BY p.paymentDate, p.paymentNum ";
    Query query = session.createQuery(q);
    query.setParameter("tin", ktr.getTin());

    query.setResultTransformer(Transformers.aliasToBean(Payment.class));
    List<Payment> paymentList = query.list();

    for (Payment payment : paymentList) {

        if (payment.getOverSum().compareTo(keyCost) <= 0) {
            KeyPayment kp = new KeyPayment();
            kp.setSerialNumber(ktr.getSerialNumber());
            kp.setPayment(payment);
            kp.setPaidSum(payment.getOverSum());
            kp.setDateCreated(dateTime);
            kp.setDateUpdated(dateTime);
            session.save(kp);

            payment.setState((short) 3);
            payment.setDateUpdated(dateTime);
            session.update(payment);

            keyCost = keyCost.subtract(payment.getOverSum());
        } else {
            KeyPayment kp = new KeyPayment();
            kp.setSerialNumber(ktr.getSerialNumber());
            kp.setPayment(payment);
            kp.setPaidSum(keyCost);
            kp.setDateCreated(dateTime);
            kp.setDateUpdated(dateTime);
            session.save(kp);

            payment.setState((short) 2);
            payment.setDateUpdated(dateTime);
            session.update(payment);

            keyCost = BigDecimal.ZERO;
        }
        if (keyCost.compareTo(BigDecimal.ZERO) <= 0) {
            break;
        }
    }
    ktr.setCommitted((short) 1);
    ktr.setDateUpdated(dateTime);
    session.update(ktr);

    transaction.commit();
    session.close();
}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * // w ww  . j a  va  2s  .com
 *
 * @param motheds
 * @param frall
 * @param num
 * @param weight
 * @return BigDecimal
 */
public BigDecimal computeFreightAll(String motheds, FreightExpressAll frall, Integer num, BigDecimal weight) {
    BigDecimal price = new BigDecimal(0);
    if (num == 0) {
        return price;
    }
    // 
    if ("0".equals(motheds)) {
        // ?
        if (num < Integer.parseInt(frall.getExpressStart().toString())) {
            //  =  +   -*
            int a = 0;
            BigDecimal temp = frall.getExpressPostageplus().multiply(new BigDecimal(a));
            price = frall.getExpressPostage().add(temp);
        } else {
            //  =  +   -*
            int a = num - Integer.parseInt(frall.getExpressStart().toString());
            BigDecimal temp = frall.getExpressPostageplus().multiply((new BigDecimal(a))
                    .divide(new BigDecimal(frall.getExpressPlusN1()), 0, BigDecimal.ROUND_UP));
            price = frall.getExpressPostage().add(temp);
        }

        return price;
    } else {
        // ??
        if (weight.compareTo(new BigDecimal(frall.getExpressStart())) == -1) {
            // ? = ? + ?-?*?
            BigDecimal a = new BigDecimal(0);
            BigDecimal temp = frall.getExpressPostageplus().multiply(a);
            price = frall.getExpressPostage().add(temp);
        } else {
            // ? = ? + ?-?*?
            BigDecimal a = weight.subtract(new BigDecimal(frall.getExpressStart()));
            BigDecimal temp = frall.getExpressPostageplus()
                    .multiply(a.divide(new BigDecimal(frall.getExpressPlusN1()), 0, BigDecimal.ROUND_UP));
            price = frall.getExpressPostage().add(temp);
        }

        return price;
    }

}

From source file:net.sourceforge.fenixedu.domain.ExecutionCourse.java

public boolean getEqualLoad(ShiftType type, CurricularCourse curricularCourse) {
    if (type != null) {
        if (type.equals(ShiftType.DUVIDAS) || type.equals(ShiftType.RESERVA)) {
            return true;
        }/*from  ww w. j  av a  2s  .  c  o  m*/
        BigDecimal ccTotalHours = curricularCourse.getTotalHoursByShiftType(type, getExecutionPeriod());
        CourseLoad courseLoad = getCourseLoadByShiftType(type);
        if ((courseLoad == null && ccTotalHours == null)
                || (courseLoad == null && ccTotalHours != null && ccTotalHours.compareTo(BigDecimal.ZERO) == 0)
                || (courseLoad != null && ccTotalHours != null
                        && courseLoad.getTotalQuantity().compareTo(ccTotalHours) == 0)) {
            return true;
        }
    }
    return false;
}

From source file:org.impotch.calcul.impot.cantonal.ge.pp.avant2010.BaremeRevenuFamille2005Test.java

private void testEgalite(String montantNonFormatte, BigDecimal montant) {
    // On teste avec un delta de 10 cts
    BigDecimal delta = new BigDecimal(montantNonFormatte).subtract(montant).abs();
    if (0 < delta.compareTo(BigDecimalUtil.CINQ_CTS)) {
        fail("Montant attendu " + montantNonFormatte + ", montant calcul " + montant);
    }/*  w  ww.j a  v  a 2s.co  m*/
}