Java Code Examples for java.math.BigDecimal#compareTo()

The following examples show how to use java.math.BigDecimal#compareTo() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Quicksql   File: RexImpTable.java    License: MIT License 6 votes vote down vote up
/** Multiplies an expression by a constant and divides by another constant,
 * optimizing appropriately.
 *
 * <p>For example, {@code multiplyDivide(e, 10, 1000)} returns
 * {@code e / 100}. */
public static Expression multiplyDivide(Expression e, BigDecimal multiplier,
    BigDecimal divider) {
  if (multiplier.equals(BigDecimal.ONE)) {
    if (divider.equals(BigDecimal.ONE)) {
      return e;
    }
    return Expressions.divide(e,
        Expressions.constant(divider.intValueExact()));
  }
  final BigDecimal x =
      multiplier.divide(divider, RoundingMode.UNNECESSARY);
  switch (x.compareTo(BigDecimal.ONE)) {
  case 0:
    return e;
  case 1:
    return Expressions.multiply(e, Expressions.constant(x.intValueExact()));
  case -1:
    return multiplyDivide(e, BigDecimal.ONE, x);
  default:
    throw new AssertionError();
  }
}
 
Example 2
Source Project: ruoyiplus   File: Arith.java    License: MIT License 6 votes vote down vote up
/**
 * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
 * 定精度,以后的数字四舍五入。
 * @param v1 被除数
 * @param v2 除数
 * @param scale 表示表示需要精确到小数点以后几位。
 * @return 两个参数的商
 */
public static double div(double v1, double v2, int scale)
{
    if (scale < 0)
    {
        throw new IllegalArgumentException(
                "The scale must be a positive integer or zero");
    }
    BigDecimal b1 = new BigDecimal(Double.toString(v1));
    BigDecimal b2 = new BigDecimal(Double.toString(v2));
    if (b1.compareTo(BigDecimal.ZERO) == 0)
    {
        return BigDecimal.ZERO.doubleValue();
    }
    return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
 
Example 3
Source Project: arbitrader   File: TradingService.java    License: MIT License 6 votes vote down vote up
BigDecimal getLimitPrice(Exchange exchange, CurrencyPair rawCurrencyPair, BigDecimal allowedVolume, Order.OrderType orderType) {
    CurrencyPair currencyPair = exchangeService.convertExchangePair(exchange, rawCurrencyPair);

    try {
        OrderBook orderBook = exchange.getMarketDataService().getOrderBook(currencyPair);
        List<LimitOrder> orders = orderType.equals(Order.OrderType.ASK) ? orderBook.getAsks() : orderBook.getBids();
        BigDecimal price;
        BigDecimal volume = BigDecimal.ZERO;

        for (LimitOrder order : orders) {
            price = order.getLimitPrice();
            volume = volume.add(order.getRemainingAmount());

            if (volume.compareTo(allowedVolume) > 0) {
                return price;
            }
        }
    } catch (IOException e) {
        LOGGER.error("IOE fetching {} {} order volume", exchange.getExchangeSpecification().getExchangeName(), currencyPair, e);
    }

    throw new RuntimeException("Not enough liquidity on exchange to fulfill required volume!");
}
 
Example 4
public static void assertRoundEquals(BigDecimal bd1, BigDecimal bd2) {
    bd1 = bd1.round(PDataType.DEFAULT_MATH_CONTEXT);
    bd2 = bd2.round(PDataType.DEFAULT_MATH_CONTEXT);
    if (bd1.compareTo(bd2) != 0) {
        fail("expected:<" + bd1 + "> but was:<" + bd2 + ">");
    }
}
 
Example 5
public boolean isTotalShiftLoadExceeded() {
    final BigDecimal totalHours = getTotalHours();
    for (final CourseLoad courseLoad : getCourseLoadsSet()) {
        if (totalHours.compareTo(courseLoad.getTotalQuantity()) == 1) {
            return true;
        }
    }
    return false;
}
 
Example 6
Source Project: datacollector   File: ForceSource.java    License: Apache License 2.0 5 votes vote down vote up
private String fixOffset(String offsetColumn, String offset) {
  com.sforce.soap.partner.Field sfdcField = ((SobjectRecordCreator)recordCreator).getFieldMetadata(sobjectType, offsetColumn);
  if (SobjectRecordCreator.DECIMAL_TYPES.contains(sfdcField.getType().toString())
      && offset.contains("E")) {
    BigDecimal val = new BigDecimal(offset);
    offset = val.toPlainString();
    if (val.compareTo(MAX_OFFSET_INT) > 0 && !offset.contains(".")) {
      // We need the ".0" suffix since Salesforce doesn't like integer
      // bigger than 2147483647
      offset += ".0";
    }
  }
  return offset;
}
 
Example 7
Source Project: sample.daytrader7   File: TradeSLSBBean.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) {
    if (!TradeConfig.getUpdateQuotePrices()) {
        return new QuoteDataBean();
    }

    if (Log.doTrace()) {
        Log.trace("TradeSLSBBean:updateQuote", symbol, changeFactor);
    }

    TypedQuery<QuoteDataBean> q = entityManager.createNamedQuery("quoteejb.quoteForUpdate",QuoteDataBean.class);
    q.setParameter(1, symbol);
    QuoteDataBean quote = q.getSingleResult();

    BigDecimal oldPrice = quote.getPrice();
    BigDecimal openPrice = quote.getOpen();

    if (oldPrice.equals(TradeConfig.PENNY_STOCK_PRICE)) {
        changeFactor = TradeConfig.PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER;
    } else if (oldPrice.compareTo(TradeConfig.MAXIMUM_STOCK_PRICE) > 0) {
        changeFactor = TradeConfig.MAXIMUM_STOCK_SPLIT_MULTIPLIER;
    }

    BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP);

    quote.setPrice(newPrice);
    quote.setChange(newPrice.subtract(openPrice).doubleValue());
    quote.setVolume(quote.getVolume() + sharesTraded);
    entityManager.merge(quote);

    context.getBusinessObject(TradeSLSBLocal.class).publishQuotePriceChange(quote, oldPrice, changeFactor, sharesTraded);
   
    return quote;
}
 
Example 8
private void fillCourseLoads(ExecutionCourse execution, CurricularCourse curricular) {
    for (ShiftType shiftType : ShiftType.values()) {
        BigDecimal totalHours = curricular.getTotalHoursByShiftType(shiftType, execution.getExecutionPeriod());
        if (totalHours != null && totalHours.compareTo(BigDecimal.ZERO) == 1) {
            CourseLoad courseLoad = execution.getCourseLoadByShiftType(shiftType);
            if (courseLoad == null) {
                new CourseLoad(execution, shiftType, null, totalHours);
            }
        }
    }
}
 
Example 9
Source Project: atlas   File: AtlasBuiltInTypes.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isValidRange(Number num) {
    final boolean ret;

    if (num instanceof Float || num instanceof Long || num instanceof Integer || num instanceof Short || num instanceof Byte) {
        ret = true;
    } else if (num instanceof Double) {
        ret = num.floatValue() >= MIN_VALUE.floatValue() && num.floatValue() <= MAX_VALUE.floatValue();
    } else {
        BigDecimal number = new BigDecimal(num.doubleValue());

        ret = (number.compareTo(MIN_VALUE) >= 0) && (number.compareTo(MAX_VALUE) <= 0);
    }

    return ret;
}
 
Example 10
Source Project: smarthome   File: NumberValue.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected boolean checkConditions(BigDecimal newValue, DecimalType oldvalue) {
    if (min != null && newValue.compareTo(min) == -1) {
        logger.trace("Number not accepted as it is below the configured minimum");
        return false;
    }
    if (max != null && newValue.compareTo(max) == 1) {
        logger.trace("Number not accepted as it is above the configured maximum");
        return false;
    }

    return true;
}
 
Example 11
/**
 * Copy payments from selected advance payment invoices to this invoice.
 *
 * @param invoice
 */
protected void copyAdvancePaymentToInvoice(Invoice invoice) throws AxelorException {
  Set<Invoice> advancePaymentInvoiceSet = invoice.getAdvancePaymentInvoiceSet();
  if (advancePaymentInvoiceSet == null) {
    return;
  }
  for (Invoice advancePaymentInvoice : advancePaymentInvoiceSet) {

    List<InvoicePayment> advancePayments = advancePaymentInvoice.getInvoicePaymentList();
    if (advancePayments == null) {
      continue;
    }
    for (InvoicePayment advancePayment : advancePayments) {

      InvoicePayment imputationPayment =
          invoicePaymentCreateService.createInvoicePayment(
              invoice,
              advancePayment.getAmount(),
              advancePayment.getPaymentDate(),
              advancePayment.getCurrency(),
              advancePayment.getPaymentMode(),
              InvoicePaymentRepository.TYPE_ADV_PAYMENT_IMPUTATION);
      advancePayment.setImputedBy(imputationPayment);
      imputationPayment.setCompanyBankDetails(advancePayment.getCompanyBankDetails());
      invoice.addInvoicePaymentListItem(imputationPayment);
      invoicePaymentRepo.save(imputationPayment);
    }
  }

  // if the sum of amounts in advance payment is greater than the amount
  // of the invoice, then we cancel the ventilation.
  List<InvoicePayment> invoicePayments = invoice.getInvoicePaymentList();
  if (invoicePayments == null || invoicePayments.isEmpty()) {
    return;
  }
  BigDecimal totalPayments =
      invoicePayments.stream().map(InvoicePayment::getAmount).reduce(BigDecimal::add).get();
  if (totalPayments.compareTo(invoice.getInTaxTotal()) > 0) {
    throw new AxelorException(
        invoice,
        TraceBackRepository.TYPE_FUNCTIONNAL,
        I18n.get(IExceptionMessage.AMOUNT_ADVANCE_PAYMENTS_TOO_HIGH));
  }
}
 
Example 12
Source Project: hbase   File: OrderedBytes.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Encode the large magnitude floating point number {@code val} using
 * the key encoding. The caller guarantees that {@code val} will be
 * finite and abs(val) >= 1.0.
 * <p>
 * A floating point value is encoded as an integer exponent {@code E}
 * and a mantissa {@code M}. The original value is equal to
 * {@code (M * 100^E)}. {@code E} is set to the smallest value
 * possible without making {@code M} greater than or equal to 1.0.
 * </p>
 * <p>
 * Each centimal digit of the mantissa is stored in a byte. If the value of
 * the centimal digit is {@code X} (hence {@code X>=0} and
 * {@code X<=99}) then the byte value will be {@code 2*X+1} for
 * every byte of the mantissa, except for the last byte which will be
 * {@code 2*X+0}. The mantissa must be the minimum number of bytes
 * necessary to represent the value; trailing {@code X==0} digits are
 * omitted. This means that the mantissa will never contain a byte with the
 * value {@code 0x00}.
 * </p>
 * <p>
 * If {@code E > 10}, then this routine writes of {@code E} as a
 * varint followed by the mantissa as described above. Otherwise, if
 * {@code E <= 10}, this routine only writes the mantissa and leaves
 * the {@code E} value to be encoded as part of the opening byte of the
 * field by the calling function.
 *
 * <pre>
 *   Encoding:  M       (if E<=10)
 *              E M     (if E>10)
 * </pre>
 * </p>
 * @param dst The destination to which encoded digits are written.
 * @param val The value to encode.
 * @return the number of bytes written.
 */
private static int encodeNumericLarge(PositionedByteRange dst, BigDecimal val) {
  // TODO: this can be done faster
  BigDecimal abs = val.abs();
  byte[] a = dst.getBytes();
  boolean isNeg = val.signum() == -1;
  final int start = dst.getPosition(), offset = dst.getOffset();
  int e = 0, d, startM;

  if (isNeg) { /* Large negative number: 0x08, ~E, ~M */
    dst.put(NEG_LARGE);
  } else { /* Large positive number: 0x22, E, M */
    dst.put(POS_LARGE);
  }

  // normalize abs(val) to determine E
  while (abs.compareTo(E32) >= 0 && e <= 350) { abs = abs.movePointLeft(32); e +=16; }
  while (abs.compareTo(E8) >= 0 && e <= 350) { abs = abs.movePointLeft(8); e+= 4; }
  while (abs.compareTo(BigDecimal.ONE) >= 0 && e <= 350) { abs = abs.movePointLeft(2); e++; }

  // encode appropriate header byte and/or E value.
  if (e > 10) { /* large number, write out {~,}E */
    putVaruint64(dst, e, isNeg);
  } else {
    if (isNeg) { /* Medium negative number: 0x13-E, ~M */
      dst.put(start, (byte) (NEG_MED_MAX - e));
    } else { /* Medium positive number: 0x17+E, M */
      dst.put(start, (byte) (POS_MED_MIN + e));
    }
  }

  // encode M by peeling off centimal digits, encoding x as 2x+1
  startM = dst.getPosition();
  // TODO: 18 is an arbitrary encoding limit. Reevaluate once we have a better handling of
  // numeric scale.
  for (int i = 0; i < 18 && abs.compareTo(BigDecimal.ZERO) != 0; i++) {
    abs = abs.movePointRight(2);
    d = abs.intValue();
    dst.put((byte) (2 * d + 1));
    abs = abs.subtract(BigDecimal.valueOf(d));
  }
  // terminal digit should be 2x
  a[offset + dst.getPosition() - 1] = (byte) (a[offset + dst.getPosition() - 1] & 0xfe);
  if (isNeg) {
    // negative values encoded as ~M
    DESCENDING.apply(a, offset + startM, dst.getPosition() - startM);
  }
  return dst.getPosition() - start;
}
 
Example 13
private boolean isBigger(BigDecimal number) {
    return number.compareTo(mMaxNumber) > 0;
}
 
Example 14
/**
 * Tack on the cost of the magical enhancement(s).
 * 
 * @param iPlus the Pluses of the primary head
 * @param altPlus the Pluses of the secondary head
 * @return cost from pluses
 */
private BigDecimal getCostFromPluses(final int iPlus, final int altPlus)
{

	if (((iPlus != 0) || (altPlus != 0)) && (JEPResourceChecker.getMissingResourceCount() == 0))
	{
		PJEP myParser = null;
		try
		{
			myParser = PjepPool.getInstance().aquire();
			myParser.addVariable("PLUS", iPlus);
			myParser.addVariable("ALTPLUS", altPlus);
			myParser.addVariable("BASECOST", getSafe(ObjectKey.COST).doubleValue());

			if (isAmmunition())
			{
				myParser.addVariable("BASEQTY", getSafe(IntegerKey.BASE_QUANTITY));
			}

			// Look for an expression for all of this item's types
			// If there is more than 1, use the most expensive.
			String costExpr;
			BigDecimal maxCost = null;
			final List<String> itemTypes = typeList();

               for (String typeMatched : itemTypes)
               {
                   costExpr = SettingsHandler.getGameAsProperty().get().getPlusCalculation(Type.getConstant(typeMatched));

                   if (costExpr != null)
                   {
                       final BigDecimal thisCost = evaluateCost(myParser, costExpr);

                       if ((maxCost == null) || (thisCost.compareTo(maxCost) > 1))
                       {
                           maxCost = thisCost;
                       }
                   }
               }

			if (maxCost != null)
			{
				return maxCost;
			}

			//
			// No cost formula found, check for catch-all definition
			//
			costExpr = SettingsHandler.getGameAsProperty().get().getPlusCalculation(Type.ANY);

			if (costExpr != null)
			{
				return evaluateCost(myParser, costExpr);
			}
		}
		finally
		{
			PjepPool.getInstance().release(myParser);
		}
	}

	return BigDecimal.ZERO;
}
 
Example 15
Source Project: scipio-erp   File: CheckOutHelper.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * SCIPIO: Verifies if current payment methods in cart are adequate enough to cover the current order, or in
 * other words the cart payments in current state can effectively be used to pay for the order.
 * <p>
 * The definition of "adequate" is abstracted by this method. Currently, it requires that the payment method
 * total equals exactly the grand total. Due to stock code function, this is only true after a successful
 * call to {@link CheckOutHelper#validatePaymentMethods} (WARN: it is NOT necessarily true after a call to
 * {@link CheckOutHelper#setCheckOutPayment}!).
 *
 * @see CheckOutHelper#validatePaymentMethods()
 */
public static boolean isPaymentsAdequate(ShoppingCart cart) {
    BigDecimal reqAmtPreParse = cart.getGrandTotal().subtract(cart.getBillingAccountAmount());
    BigDecimal selectedPmnt = cart.getPaymentTotal();

    BigDecimal selectedPaymentTotal = selectedPmnt.setScale(scale, rounding);
    BigDecimal requiredAmount = reqAmtPreParse.setScale(scale, rounding);

    return (requiredAmount.compareTo(selectedPaymentTotal) == 0);
}
 
Example 16
Source Project: ph-commons   File: MathHelper.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * @param aValue
 *        Value to compare. May not be <code>null</code>.
 * @return <code>true</code> if the value is &ge; 0.
 */
public static boolean isGE0 (@Nonnull final BigDecimal aValue)
{
  return aValue.compareTo (BigDecimal.ZERO) >= 0;
}
 
Example 17
Source Project: smart-admin   File: SmartBigDecimalUtil.java    License: MIT License 2 votes vote down vote up
/**
 * 比较 num1 是否大于 num2
 *
 * @param num1
 * @param num2
 * @return boolean
 */
public static boolean isGreaterThan(BigDecimal num1, BigDecimal num2) {
    return num1.compareTo(num2) == 1;
}
 
Example 18
Source Project: ph-commons   File: MathHelper.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * @param aValue
 *        Value to compare. May not be <code>null</code>.
 * @return <code>true</code> if the value is &lt; 100.
 */
public static boolean isLT100 (@Nonnull final BigDecimal aValue)
{
  return aValue.compareTo (CGlobal.BIGDEC_100) < 0;
}
 
Example 19
Source Project: ph-commons   File: MathHelper.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * @param aValue
 *        Value to compare. May not be <code>null</code>.
 * @return <code>true</code> if the value is &le; 100.
 */
public static boolean isLE100 (@Nonnull final BigDecimal aValue)
{
  return aValue.compareTo (CGlobal.BIGDEC_100) <= 0;
}
 
Example 20
Source Project: yes-cart   File: MoneyUtils.java    License: Apache License 2.0 votes vote down vote up
/**
 * Check if positive.
 *
 * @param value  value
 *
 * @return true if value is greater than zero (null safe)
 */
public static boolean isPositive(final BigDecimal value) {

    return value != null && value.compareTo(BigDecimal.ZERO) > 0;

}