Example usage for java.math BigDecimal equals

List of usage examples for java.math BigDecimal equals

Introduction

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

Prototype

@Override
public boolean equals(Object x) 

Source Link

Document

Compares this BigDecimal with the specified Object for equality.

Usage

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

private void checkStretchesSumOneHundredPercent() {
    List<Stretch> stretches = getStretchesPlusConsolidated();
    BigDecimal sumOfProportions = stretches.isEmpty() ? BigDecimal.ZERO
            : last(stretches).getAmountWorkPercentage();
    BigDecimal left = calculateLeftFor(sumOfProportions);

    if (!left.equals(BigDecimal.ZERO)) {
        throw new IllegalStateException(_("Stretches must sum 100%"));
    }//from w ww .ja  v  a2  s.co m
}

From source file:net.sourceforge.happybank.control.TransferFunds.java

/**
 * Transfer the funds./*  w ww  .  j  a v a 2s  . c o  m*/
 * 
 * @param request the request
 * @param response the response
 * @throws ServletException on servlet failure
 * @throws IOException on IO failure
 */
@SuppressWarnings("unchecked")
protected void performTask(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        // parameters:

        HttpSession session = request.getSession(false);
        String accountID1 = (String) session.getAttribute("accountNumber");
        String accountID2 = (String) request.getParameter("destinationAccount").toString();

        // get all of the customers accounts
        String customerId = (String) session.getAttribute("customerNumber");
        List<Account> accounts = getBank().getAccounts(customerId);

        // get the amount to transfer
        BigDecimal amount = new BigDecimal(request.getParameter("amount"));

        // set response type and create JSON object
        response.setContentType("application/json");
        PrintWriter rOut = response.getWriter();
        JSONObject jObj = new JSONObject();
        jObj.put("code", new Integer(0)); // assume failure

        // control logic:

        if (amount.equals(new BigDecimal(0.00))) {
            jObj.put("message", "A valid <b>amount</b> is required.");
            jObj.put("field", "amount");
            rOut.println(jObj);
            rOut.close();
        }

        getBank().transfer(accountID1, accountID2, amount);

        jObj.put("code", new Integer(1)); // success
        rOut.println(jObj);
        rOut.close();
    } catch (Exception ex) {
        response.setContentType("application/json");
        PrintWriter rOut = response.getWriter();
        JSONObject jObj = new JSONObject();
        jObj.put("code", new Integer(0));
        jObj.put("message", ex.getMessage());
        rOut.println(jObj);
        rOut.close();
    }
}

From source file:org.jpos.gl.rule.DoubleEntry.java

private void checkEntries(GLTransaction txn, short layer) throws GLException {
    List list = txn.getEntries();
    // if (list.size() < 2) 
    //     throw new GLException ("too few entries (" + list.size() + ")");
    BigDecimal debits = ZERO;
    BigDecimal credits = ZERO;/*from w  ww  . j a  va  2  s.  c o  m*/
    Iterator iter = list.iterator();

    while (iter.hasNext()) {
        GLEntry entry = (GLEntry) iter.next();
        if (entry.getLayer() == layer) {
            if (entry.isDebit())
                debits = debits.add(entry.getAmount());
            else
                credits = credits.add(entry.getAmount());
        }
    }
    if (!debits.equals(credits)) {
        throw new GLException("Transaction does not balance. debits=" + debits.toString() + ", credits="
                + credits.toString());
    }
}

From source file:no.abmu.questionnaire.domain.data.BigDecimalFieldData.java

public void setBigDecimalValue(BigDecimal bigDecimal) {
    //        logger.debug("Executing setBigDecimalValue code=[" + getCode() + "] bigDecimalValue=[" + bigDecimal + "]");
    if (bigDecimal == null) {
        if (this.bigDecimalValue != null) {
            this.bigDecimalValue = null;
        }/*from www . j ava2 s.  co m*/
        return;
    }
    if (bigDecimal.equals(this.bigDecimalValue)) {
        return;
    }
    this.bigDecimalValue = bigDecimal;
}

From source file:org.egov.wtms.web.controller.application.MeterReadingController.java

private BigDecimal calculateAmountTobePaid(final WaterConnectionDetails waterConnectionDetails,
        final BigDecimal noOfUnitsPerMonth) {
    MeteredRates meteredRates = null;/*w  w w .j  a  v a 2  s.c o  m*/
    UsageSlab usageSlab = null;
    if (!noOfUnitsPerMonth.equals(BigDecimal.ZERO))
        usageSlab = usageSlabService.getUsageSlabForWaterVolumeConsumed(
                waterConnectionDetails.getUsageType().getName(), noOfUnitsPerMonth.longValue());
    if (usageSlab != null && usageSlab.getSlabName() != null)
        meteredRates = meteredRatesService.findBySlabName(usageSlab.getSlabName());
    else if (!noOfUnitsPerMonth.equals(BigDecimal.ZERO))
        throw new ApplicationRuntimeException("err.usageslab.not.present");
    BigDecimal amountToBeCollected;
    if (meteredRates == null || meteredRates.getSlabName() == null)
        throw new ApplicationRuntimeException(ERROR_METER_RATE_NOT_PRESENT);
    else
        amountToBeCollected = getAmountToBeCollected(meteredRates, usageSlab, noOfUnitsPerMonth);
    return amountToBeCollected;
}

From source file:de.hybris.platform.b2bacceleratorservices.jalo.promotions.ProductPriceDiscountPromotionByPaymentType.java

@Override
public List<PromotionResult> evaluate(final SessionContext ctx, final PromotionEvaluationContext promoContext) {
    final List<PromotionResult> promotionResults = new ArrayList<PromotionResult>();
    // Find all valid products in the cart
    final PromotionsManager.RestrictionSetResult restrictionResult = this.findEligibleProductsInBasket(ctx,
            promoContext);//from   w  w  w .ja  va 2 s  .  c om

    if (restrictionResult.isAllowedToContinue() && !restrictionResult.getAllowedProducts().isEmpty()) {
        final PromotionOrderView view = promoContext.createView(ctx, this,
                restrictionResult.getAllowedProducts());
        final AbstractOrder order = promoContext.getOrder();

        for (final PromotionOrderEntry entry : view.getAllEntries(ctx)) {
            // Get the next order entry
            final long quantityToDiscount = entry.getQuantity(ctx);
            if (quantityToDiscount > 0) {
                final long quantityOfOrderEntry = entry.getBaseOrderEntry().getQuantity(ctx).longValue();

                // The adjustment to the order entry
                final double originalUnitPrice = entry.getBasePrice(ctx).doubleValue();
                final double originalEntryPrice = quantityToDiscount * originalUnitPrice;

                final Currency currency = promoContext.getOrder().getCurrency(ctx);
                Double discountPriceValue;

                final EnumerationValue paymentType = B2BAcceleratorServicesManager.getInstance()
                        .getPaymentType(ctx, order);

                if (paymentType != null
                        && StringUtils.equalsIgnoreCase(paymentType.getCode(), getPaymentType().getCode())) {
                    promoContext.startLoggingConsumed(this);
                    discountPriceValue = this.getPriceForOrder(ctx, this.getProductDiscountPrice(ctx),
                            promoContext.getOrder(),
                            ProductPriceDiscountPromotionByPaymentType.PRODUCTDISCOUNTPRICE);

                    final BigDecimal adjustedEntryPrice = Helper.roundCurrencyValue(ctx, currency,
                            originalEntryPrice - (quantityToDiscount * discountPriceValue.doubleValue()));
                    // Calculate the unit price and round it
                    final BigDecimal adjustedUnitPrice = Helper.roundCurrencyValue(ctx, currency,
                            adjustedEntryPrice.equals(BigDecimal.ZERO) ? BigDecimal.ZERO
                                    : adjustedEntryPrice.divide(BigDecimal.valueOf(quantityToDiscount),
                                            RoundingMode.HALF_EVEN));

                    for (final PromotionOrderEntryConsumed poec : view.consume(ctx, quantityToDiscount)) {
                        poec.setAdjustedUnitPrice(ctx, adjustedUnitPrice.doubleValue());
                    }

                    final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(ctx,
                            this, promoContext.getOrder(), 1.0F);
                    result.setConsumedEntries(ctx, promoContext.finishLoggingAndGetConsumed(this, true));
                    final BigDecimal adjustment = Helper.roundCurrencyValue(ctx, currency,
                            adjustedEntryPrice.subtract(BigDecimal.valueOf(originalEntryPrice)));
                    final PromotionOrderEntryAdjustAction poeac = PromotionsManager.getInstance()
                            .createPromotionOrderEntryAdjustAction(ctx, entry.getBaseOrderEntry(),
                                    quantityOfOrderEntry, adjustment.doubleValue());
                    result.addAction(ctx, poeac);
                    promotionResults.add(result);
                }
            }
        }
        final long remainingCount = view.getTotalQuantity(ctx);
        if (remainingCount > 0) {
            promoContext.startLoggingConsumed(this);
            view.consume(ctx, remainingCount);
            final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(ctx, this,
                    promoContext.getOrder(), 0.5F);
            result.setConsumedEntries(ctx, promoContext.finishLoggingAndGetConsumed(this, false));
            promotionResults.add(result);
        }
    }
    return promotionResults;
}

From source file:com.konakart.bl.modules.ordertotal.productdiscount.ProductDiscount.java

/**
 * Returns an object containing the promotion discount. This method is used to apply the
 * promotion to a single product.//from   w  w  w  . j  a va  2 s.co  m
 * 
 * @param product
 * @param promotion
 * @return Returns a PromotionResult object
 * @throws Exception
 */
public PromotionResult getPromotionResult(Product product, Promotion promotion) throws Exception {

    // Actual discount. Could be a percentage or an amount.
    BigDecimal discountApplied = getCustomBigDecimal(promotion.getCustom3(), 3);

    // Don't bother going any further if there is no discount
    if (discountApplied == null || discountApplied.equals(new BigDecimal(0))) {
        return null;
    }

    // If set to true it is a percentage. Otherwise it is an amount.
    boolean percentageDiscount = getCustomBoolean(promotion.getCustom4(), 4);

    // If set to true, discount is applied to pre-tax value. Only relevant for
    // percentage discount.
    boolean applyBeforeTax = getCustomBoolean(promotion.getCustom5(), 5);

    PromotionResult pd = new PromotionResult();
    pd.setPromotionId(promotion.getId());
    pd.setOrderTotalCode(code);
    pd.setValue(discountApplied);
    pd.setApplyBeforeTax(applyBeforeTax);
    pd.setPercentageDiscount(percentageDiscount);

    return pd;

}

From source file:com.microsoft.office.core.AbstractPrimitiveTest.java

protected void decimal(final String entity, final String propertyName, final BigDecimal check) {
    final ODataPrimitiveValue opv = readPrimitiveValue(entity, propertyName);
    assertEquals(EdmSimpleType.Decimal.toString(), opv.getTypeName());

    final BigDecimal value = opv.<BigDecimal>toCastValue();
    assertNotNull(value);/*from ww  w. j  av a 2s  . co m*/
    assertTrue(check.equals(value));
}

From source file:org.sonar.plugins.qualityprofileprogression.batch.ProfileProgressionDecorator.java

protected int getProjectsViolationPercentage(DecoratorContext context) {
    List<Violation> violations = context.getViolations();
    logger.debug("Found {} violations.", violations.size());

    List<ActiveRule> rules = profile.getActiveRules();
    logger.debug("Found {} rules.", rules.size());

    // get base measures
    BigDecimal numberOfViolations = new BigDecimal(violations.size());
    BigDecimal numberOfRules = new BigDecimal(rules.size());

    // get violation ratio
    BigDecimal projectViolationDecimal = null;
    if (numberOfRules.equals(new BigDecimal(0)))
    // no rules so 0% violations
    {//  ww w .  ja  va  2 s  .  c om
        projectViolationDecimal = new BigDecimal(0);
    } else {
        projectViolationDecimal = numberOfViolations.divide(numberOfRules);
    }

    // convert to percentage
    int projectViolationPercentage = projectViolationDecimal.multiply(new BigDecimal(100)).intValue();

    logger.debug("Project's % violations: {}", projectViolationPercentage);

    return projectViolationPercentage;
}

From source file:pyromaniac.Algorithm.BalzerOUCallFrequencyTable.java

public void loadProbabilities(String probFile) {
    try {/*from   ww  w  .ja v  a 2s .  c o  m*/
        URL url = getClass().getResource(probFile);

        //      System.out.println("Path; " + url.getPath());

        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        String line = in.readLine();

        String header = null;
        int segment = -1;
        HashMap<Integer, BigDecimal[]> probsForCurrSegment = null;

        while (line != null) {
            if (header == null || !line.contains(",")) {
                if (header != null) {
                    this.probabilities.put(segment, probsForCurrSegment);
                } else {
                    //System.out.println("header was null");
                }
                probsForCurrSegment = new HashMap<Integer, BigDecimal[]>();
                header = line;
                segment = Integer.parseInt(header);
            } else {
                String[] probabilities = line.split(",");

                if (probabilities.length != 4)
                    throw new Exception("Probability file has incorrect format");

                BigDecimal[] probs = new BigDecimal[probabilities.length - 1];

                int mode = Integer.parseInt(probabilities[0]);

                BigDecimal sumProbs = new BigDecimal("0").setScale(SCALE, BigDecimal.ROUND_HALF_UP);

                for (int i = 1; i < probabilities.length; i++) {
                    probs[i - 1] = new BigDecimal(probabilities[i]).setScale(SCALE, BigDecimal.ROUND_HALF_UP);

                    sumProbs = sumProbs.add(probs[i - 1]);
                }

                if (!sumProbs.equals(new BigDecimal("1").setScale(SCALE, BigDecimal.ROUND_HALF_UP))) {
                    probs[OUFrequencyTable.GREATER_THAN] = probs[OUFrequencyTable.GREATER_THAN].divide(sumProbs,
                            SCALE, BigDecimal.ROUND_HALF_UP);
                    probs[OUFrequencyTable.EQUAL_TO] = probs[OUFrequencyTable.EQUAL_TO].divide(sumProbs, SCALE,
                            BigDecimal.ROUND_HALF_UP);
                    probs[OUFrequencyTable.LESS_THAN] = probs[OUFrequencyTable.LESS_THAN].divide(sumProbs,
                            SCALE, BigDecimal.ROUND_HALF_UP);
                }

                probsForCurrSegment.put(mode, probs);
            }

            line = in.readLine();
        }

        //add the last cycle
        this.probabilities.put(segment, probsForCurrSegment);
    } catch (NumberFormatException nfe) {
        nfe.printStackTrace();
    } catch (IOException ie) {
        ie.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}