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:edu.usu.sdl.openstorefront.core.sort.BeanComparator.java

@Override
public int compare(T o1, T o2) {
    T obj1 = o1;/*from   w  w  w  .  jav a2 s. c  o  m*/
    T obj2 = o2;
    if (OpenStorefrontConstant.SORT_ASCENDING.equals(sortDirection)) {
        obj1 = o2;
        obj2 = o1;
    }

    if (obj1 != null && obj2 == null) {
        return 1;
    } else if (obj1 == null && obj2 != null) {
        return -1;
    } else if (obj1 != null && obj2 != null) {
        if (StringUtils.isNotBlank(sortField)) {
            try {
                Object o = obj1;
                Class<?> c = o.getClass();

                Field f = c.getDeclaredField(sortField);
                f.setAccessible(true);
                if (f.get(o) instanceof Date) {
                    int compare = 0;
                    DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
                    if (BeanUtils.getProperty(obj1, sortField) != null
                            && BeanUtils.getProperty(obj2, sortField) == null) {
                        return 1;
                    } else if (BeanUtils.getProperty(obj1, sortField) == null
                            && BeanUtils.getProperty(obj2, sortField) != null) {
                        return -1;
                    } else if (BeanUtils.getProperty(obj1, sortField) != null
                            && BeanUtils.getProperty(obj2, sortField) != null) {
                        Date value1 = format.parse(BeanUtils.getProperty(obj1, sortField));
                        Date value2 = format.parse(BeanUtils.getProperty(obj2, sortField));
                        if (value1 != null && value2 == null) {
                            return 1;
                        } else if (value1 == null && value2 != null) {
                            return -1;
                        } else if (value1 != null && value2 != null) {

                            compare = value1.compareTo(value2);
                        }
                    }
                    return compare;
                } else {
                    try {
                        String value1 = BeanUtils.getProperty(obj1, sortField);
                        String value2 = BeanUtils.getProperty(obj2, sortField);
                        if (value1 != null && value2 == null) {
                            return 1;
                        } else if (value1 == null && value2 != null) {
                            return -1;
                        } else if (value1 != null && value2 != null) {

                            if (StringUtils.isNotBlank(value1) && StringUtils.isNotBlank(value2)
                                    && StringUtils.isNumeric(value1) && StringUtils.isNumeric(value2)) {

                                BigDecimal numValue1 = new BigDecimal(value1);
                                BigDecimal numValue2 = new BigDecimal(value2);
                                return numValue1.compareTo(numValue2);
                            } else {
                                return value1.toLowerCase().compareTo(value2.toLowerCase());
                            }
                        }
                    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                        log.log(Level.FINER, MessageFormat.format("Sort field doesn''t exist: {0}", sortField));
                    }
                }
            } catch (ParseException | NoSuchFieldException | SecurityException | IllegalArgumentException
                    | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                try {
                    String value1 = BeanUtils.getProperty(obj1, sortField);
                    String value2 = BeanUtils.getProperty(obj2, sortField);
                    if (value1 != null && value2 == null) {
                        return 1;
                    } else if (value1 == null && value2 != null) {
                        return -1;
                    } else if (value1 != null && value2 != null) {

                        if (StringUtils.isNotBlank(value1) && StringUtils.isNotBlank(value2)
                                && StringUtils.isNumeric(value1) && StringUtils.isNumeric(value2)) {

                            BigDecimal numValue1 = new BigDecimal(value1);
                            BigDecimal numValue2 = new BigDecimal(value2);
                            return numValue1.compareTo(numValue2);
                        } else {
                            return value1.toLowerCase().compareTo(value2.toLowerCase());
                        }
                    }
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex2) {
                    log.log(Level.FINER, MessageFormat.format("Sort field doesn''t exist: {0}", sortField));
                }
            }
        }
    }
    return 0;
}

From source file:org.dash.wallet.integration.uphold.ui.UpholdWithdrawalDialog.java

@SuppressLint("SetTextI18n")
private void showCommitTransactionConfirmationDialog(boolean deductFeeFromAmount) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
    dialogBuilder.setTitle(R.string.uphold_withdrawal_confirm_title);

    View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.uphold_confirm_transaction_dialog,
            null);/*from  ww  w. j a v  a 2 s.  co m*/
    TextView amountTxt = contentView.findViewById(R.id.uphold_withdrawal_amount);
    TextView feeTxt = contentView.findViewById(R.id.uphold_withdrawal_fee);
    TextView totalTxt = contentView.findViewById(R.id.uphold_withdrawal_total);
    View deductFeeDisclaimer = contentView
            .findViewById(R.id.uphold_withdrawal_confirmation_fee_deduction_disclaimer);

    BigDecimal fee = transaction.getOrigin().getFee();
    final BigDecimal baseAmount = transaction.getOrigin().getBase();
    final BigDecimal total = transaction.getOrigin().getAmount();

    if (total.compareTo(balance) > 0) {
        transfer(balance.subtract(fee), true);
        return;
    }

    amountTxt.setText(baseAmount.toPlainString());
    feeTxt.setText(fee.toPlainString());
    totalTxt.setText(total.toPlainString());

    if (deductFeeFromAmount) {
        deductFeeDisclaimer.setVisibility(View.VISIBLE);
    }

    dialogBuilder.setView(contentView);
    dialogBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            commitTransaction();
        }
    });

    dialogBuilder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            transaction = null;
        }
    });
    dialogBuilder.setCancelable(false);
    dialogBuilder.show();
}

From source file:com.premiumminds.billy.core.services.builders.impl.GenericInvoiceBuilderImpl.java

@Override
@NotOnUpdate/* w  w w  .ja  va 2  s.co  m*/
public TBuilder setSettlementDiscount(BigDecimal discount) {
    Validate.isTrue(discount == null || discount.compareTo(BigDecimal.ZERO) >= 0,
            GenericInvoiceBuilderImpl.LOCALIZER.getString("field.discount")); // TODO
    // message
    this.getTypeInstance().setSettlementDiscount(discount);
    return this.getBuilder();
}

From source file:no.abmu.questionnaire.domain.validators.ValueLevelValidator.java

public void validate(FieldData fieldData, Errors errors) {
    BigDecimal bigDecimalValue = ((BigDecimalFieldData) fieldData).getBigDecimalValue();
    if (bigDecimalValue == null) {
        logger.debug("Value " + fieldData + " for field " + fieldData.getCode() + " validated OK");
    } else {/*from  ww w  .  j a  v a2  s. c  o  m*/
        if (bigDecimalValue.compareTo(lessThan) < 0) {
            errors.rejectValue(getFieldName(fieldData), "validation.must.be.less.than",
                    getErrorMessageArguments(bigDecimalValue), "Int value for post " + fieldData.getCode()
                            + " is " + bigDecimalValue + " it it has to be less than " + lessThan);
        } else if (bigDecimalValue.compareTo(greaterThan) > 0) {
            errors.rejectValue(getFieldName(fieldData), "validation.must.be.more.than",
                    getErrorMessageArguments(bigDecimalValue), "Int value for post " + fieldData.getCode()
                            + " is " + bigDecimalValue + " it it has to be greater than " + greaterThan);
        } else {
            logger.debug("Value " + fieldData + " for field " + fieldData.getCode() + " validated OK");
        }
    }
}

From source file:com.creditcloud.carinsurance.local.CarInsuranceFeeLocalBean.java

/**
 * ?/*from ww w . j a  v  a 2 s  . c o  m*/
 * @param repayment
 * @return 
 */
public BigDecimal overdueFee(CarInsuranceRepayment repayment) {
    if (repayment == null) {
        return BigDecimal.ZERO;
    }
    if (LocalDate.now().toDate().compareTo(repayment.getDueDate()) <= 0) {
        return BigDecimal.ZERO;
    }
    BigDecimal days = BigDecimal.ZERO;
    //
    if (repayment.getRepayDate() != null) {
        long repayTime = repayment.getRepayDate().getTime();
        long dueTime = repayment.getDueDate().getTime();
        days = BigDecimal.valueOf((repayTime - dueTime) / DateUtils.MILLIS_PER_DAY);
        if (days.compareTo(BigDecimal.ZERO) < 0) {
            return BigDecimal.ZERO;
        }
    } else {
        long nowTime = LocalDate.now().plusDays(1).toDate().getTime();
        long dueTime = repayment.getDueDate().getTime();
        days = BigDecimal.valueOf((nowTime - dueTime) / DateUtils.MILLIS_PER_DAY);
    }
    BigDecimal penaltyAmount = BigDecimal.ZERO;
    //???
    Fee overduePenaltyFee = configManager.getCarInsuranceConfig().getPenaltyFee();
    penaltyAmount = FeeUtils.calculate(overduePenaltyFee, repayment.getAmountPrincipal()).multiply(days)
            .setScale(NumberConstant.DEFAULT_SCALE, NumberConstant.ROUNDING_MODE);
    return penaltyAmount;
}

From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.java

public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");

    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);

    String token = (String) paramMap.get("TOKEN");
    WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token));
    ShoppingCart cart = null;/*from  w  w w.  ja  v a 2  s  .  c o  m*/
    if (weakCart != null) {
        cart = weakCart.get();
    }
    if (cart == null) {
        Debug.logError("Could locate the ShoppingCart for token " + token, module);
        return ServiceUtil.returnSuccess();
    }
    // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and
    // then delete once we're done, now is not the time to worry about updating everything
    String contactMechId = null;
    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("address1", paramMap.get("SHIPTOSTREET"));
    inMap.put("address2", paramMap.get("SHIPTOSTREET2"));
    inMap.put("city", paramMap.get("SHIPTOCITY"));
    String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY");
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator);
    if (countryGeoId == null) {
        return ServiceUtil.returnSuccess();
    }
    inMap.put("countryGeoId", countryGeoId);
    inMap.put("stateProvinceGeoId",
            parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator));
    inMap.put("postalCode", paramMap.get("SHIPTOZIP"));

    try {
        GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system")
                .cache().queryOne();
        inMap.put("userLogin", userLogin);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    boolean beganTransaction = false;
    Transaction parentTransaction = null;
    try {
        parentTransaction = TransactionUtil.suspend();
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, module);
    }
    try {
        Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap);
        contactMechId = (String) outMap.get("contactMechId");
    } catch (GenericServiceException e) {
        Debug.logError(e.getMessage(), module);
        return ServiceUtil.returnSuccess();
    }
    try {
        TransactionUtil.commit(beganTransaction);
        if (parentTransaction != null)
            TransactionUtil.resume(parentTransaction);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    // clone the cart so we can modify it temporarily
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    String oldShipAddress = cart.getShippingContactMechId();
    coh.setCheckOutShippingAddress(contactMechId);
    ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0);
    int line = 0;
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "CallbackResponse");

    for (GenericValue shipMethod : estWrapper.getShippingMethods()) {
        BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod);
        //Check that we have a valid estimate (allowing zero value estimates for now)
        if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) {
            continue;
        }
        cart.setAllShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId"));
        cart.setAllCarrierPartyId(shipMethod.getString("partyId"));
        try {
            coh.calcAndAddTax();
        } catch (GeneralException e) {
            Debug.logError(e, module);
            continue;
        }
        String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description");
        encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel);
        encoder.add("L_SHIPPINGOPTIONAMOUNT" + line,
                estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        // Just make this first one default for now
        encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false");
        encoder.add("L_TAXAMT" + line,
                cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        line++;
    }
    String responseMsg = null;
    try {
        responseMsg = encoder.encode();
    } catch (PayPalException e) {
        Debug.logError(e, module);
    }
    if (responseMsg != null) {
        try {
            response.setContentLength(responseMsg.getBytes("UTF-8").length);
        } catch (UnsupportedEncodingException e) {
            Debug.logError(e, module);
        }

        try {
            Writer writer = response.getWriter();
            writer.write(responseMsg);
            writer.close();
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }

    // Remove the temporary ship address
    try {
        GenericValue postalAddress = EntityQuery.use(delegator).from("PostalAddress")
                .where("contactMechId", contactMechId).queryOne();
        postalAddress.remove();
        GenericValue contactMech = EntityQuery.use(delegator).from("ContactMech")
                .where("contactMechId", contactMechId).queryOne();
        contactMech.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    coh.setCheckOutShippingAddress(oldShipAddress);
    return ServiceUtil.returnSuccess();
}

From source file:nl.strohalm.cyclos.entities.accounts.transactions.Transfer.java

/**
 * When the amount is negative (i.e. chargeback), returns the to account instead
 *///from   w w w.  j a  v  a 2  s  .co  m
public Account getActualFrom() {
    final BigDecimal amount = getAmount();
    return amount == null || amount.compareTo(BigDecimal.ZERO) >= 0 ? getFrom() : getTo();
}

From source file:nl.strohalm.cyclos.entities.accounts.transactions.Transfer.java

/**
 * When the amount is negative (i.e. chargeback), returns the from account instead
 *///  ww  w  .  j  a  v a2s .c om
public Account getActualTo() {
    final BigDecimal amount = getAmount();
    return amount == null || amount.compareTo(BigDecimal.ZERO) >= 0 ? getTo() : getFrom();
}

From source file:org.jpox.util.SQLFormat.java

public void testRandomValues() throws Throwable {
        Random rnd = new Random(0L);

        for (int i = 0; i < NUM_RANDOM_CASES; ++i) {
            BigDecimal bd1 = new BigDecimal(new BigInteger(128, rnd), rnd.nextInt(100));
            String s = SQLFormat.format(bd1);
            BigDecimal bd2 = new BigDecimal(SQLFormat.format(bd1));

            assertEquals("Formatting " + bd1 + " yielded " + s + " which doesn't equal", 0, bd1.compareTo(bd2));
        }//from   ww w.  ja  v a 2s .c om
    }

From source file:edu.macalester.tagrelatedness.KendallsCorrelation.java

public BigDecimal get(BigDecimal n) {

    // Make sure n is a positive number

    if (n.compareTo(ZERO) <= 0) {
        throw new IllegalArgumentException();
    }/*ww  w . java 2s  .  c o  m*/

    BigDecimal initialGuess = getInitialApproximation(n);
    trace("Initial guess " + initialGuess.toString());
    BigDecimal lastGuess = ZERO;
    BigDecimal guess = new BigDecimal(initialGuess.toString());

    // Iterate

    iterations = 0;
    boolean more = true;
    while (more) {
        lastGuess = guess;
        guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP);
        guess = guess.add(lastGuess);
        guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP);
        trace("Next guess " + guess.toString());
        error = n.subtract(guess.multiply(guess));
        if (++iterations >= maxIterations) {
            more = false;
        } else if (lastGuess.equals(guess)) {
            more = error.abs().compareTo(ONE) >= 0;
        }
    }
    return guess;

}