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:ddf.catalog.validation.impl.validator.RangeValidator.java

/**
 * Creates a {@code RangeValidator} with an <strong>inclusive</strong> range and the provided
 * epsilon.//from w ww.  j a v a  2 s .c om
 * <p>
 * Uses the provided epsilon on both sides of the range to account for floating point
 * representation inaccuracies, so the range is really [min - epsilon, max + epsilon].
 *
 * @param min     the minimum allowable value (inclusive), cannot be null
 * @param max     the maximum allowable value (inclusive), cannot be null and must be greater
 *                than {@code min}
 * @param epsilon the epsilon value, cannot be null and must be positive
 * @throws IllegalArgumentException if {@code max} is not greater than {@code min},
 *                                  {@code epsilon} is not positive, or if any argument is null
 */
public RangeValidator(final BigDecimal min, final BigDecimal max, final BigDecimal epsilon) {
    Preconditions.checkArgument(min != null, "The minimum cannot be null.");
    Preconditions.checkArgument(max != null, "The maximum cannot be null.");
    Preconditions.checkArgument(epsilon != null, "The epsilon cannot be null.");
    Preconditions.checkArgument(min.compareTo(max) == -1, "The maximum must be greater than the minimum.");
    Preconditions.checkArgument(epsilon.compareTo(BigDecimal.ZERO) == 1, "The epsilon must be greater than 0.");

    this.min = min.subtract(epsilon);
    this.max = max.add(epsilon);
}

From source file:jgnash.ui.report.compiled.IncomeExpensePieChart.java

private PieDataset createPieDataSet(Account a) {
    DefaultPieDataset returnValue = new DefaultPieDataset();
    if (a != null) {

        BigDecimal total = a.getTreeBalance(startField.getLocalDate(), endField.getLocalDate(),
                a.getCurrencyNode());/*w  ww. j  ava 2  s.c  o  m*/

        // abs() on all values won't work if children aren't of uniform sign,
        // then again, this chart is not right to display those trees
        boolean negate = total != null && total.floatValue() < 0;

        // accounts may have balances independent of their children
        BigDecimal value = a.getBalance(startField.getLocalDate(), endField.getLocalDate());

        if (value.compareTo(BigDecimal.ZERO) != 0) {
            returnValue.setValue(a, negate ? value.negate() : value);
        }

        for (final Account child : a.getChildren(Comparators.getAccountByCode())) {
            value = child.getTreeBalance(startField.getLocalDate(), endField.getLocalDate(),
                    a.getCurrencyNode());

            if (showEmptyCheck.isSelected() || value.compareTo(BigDecimal.ZERO) != 0) {
                returnValue.setValue(child, negate ? value.negate() : value);
            }
        }
    }
    return returnValue;
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFJUInt64Editor.java

public boolean isEditValid() {
    final String S_ProcName = "isEditValid";
    if (!hasValue()) {
        setValue(null);/*from  w w w . j a  v a 2  s .  c o  m*/
        return (true);
    }

    boolean retval = super.isEditValid();
    if (retval) {
        try {
            commitEdit();
        } catch (ParseException e) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Field is not valid - " + e.getMessage(), e);

        }
        Object obj = getValue();
        if (obj == null) {
            retval = false;
        } else if (obj instanceof Short) {
            Short s = (Short) obj;
            BigDecimal v = new BigDecimal(s.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Integer) {
            Integer i = (Integer) obj;
            BigDecimal v = new BigDecimal(i.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Long) {
            Long l = (Long) obj;
            BigDecimal v = new BigDecimal(l.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else if (obj instanceof BigDecimal) {
            BigDecimal v = (BigDecimal) obj;
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Number) {
            Number n = (Number) obj;
            BigDecimal v = new BigDecimal(n.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else {
            throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException(getClass(), S_ProcName,
                    "EditedValue", obj, "Short, Integer, Long, BigDecimal or Number");
        }
    }
    return (retval);
}

From source file:org.apache.hive.storage.jdbc.spitter.DecimalIntervalSplitter.java

@Override
public List<MutablePair<String, String>> getIntervals(String lowerBound, String upperBound, int numPartitions,
        TypeInfo typeInfo) {//w w  w.  j  av  a2  s.  c  o  m
    List<MutablePair<String, String>> intervals = new ArrayList<>();
    DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) typeInfo;
    int scale = decimalTypeInfo.getScale();
    BigDecimal decimalLower = new BigDecimal(lowerBound);
    BigDecimal decimalUpper = new BigDecimal(upperBound);
    BigDecimal decimalInterval = (decimalUpper.subtract(decimalLower)).divide(new BigDecimal(numPartitions),
            MathContext.DECIMAL64);
    BigDecimal splitDecimalLower, splitDecimalUpper;
    for (int i = 0; i < numPartitions; i++) {
        splitDecimalLower = decimalLower.add(decimalInterval.multiply(new BigDecimal(i))).setScale(scale,
                RoundingMode.HALF_EVEN);
        splitDecimalUpper = decimalLower.add(decimalInterval.multiply(new BigDecimal(i + 1))).setScale(scale,
                RoundingMode.HALF_EVEN);
        if (splitDecimalLower.compareTo(splitDecimalUpper) < 0) {
            intervals.add(new MutablePair<String, String>(splitDecimalLower.toPlainString(),
                    splitDecimalUpper.toPlainString()));
        }
    }
    return intervals;
}

From source file:org.openvpms.archetype.rules.finance.till.TillRules.java

/**
 * Adds an adjustment to a till, if required.
 *
 * @param balance   the till balance act
 * @param cashFloat the new cash float/*from  w  ww  .  ja v a2 s. c om*/
 */
private void addAdjustment(FinancialAct balance, BigDecimal cashFloat, Till till) {
    BigDecimal lastCashFloat = till.getTillFloat();

    BigDecimal diff = cashFloat.subtract(lastCashFloat);
    if (diff.compareTo(BigDecimal.ZERO) != 0) {
        // need to generate an adjustment, and associate it with the balance
        boolean credit = (lastCashFloat.compareTo(cashFloat) > 0);
        Act adjustment = createTillBalanceAdjustment(till.getEntity(), diff.abs(), credit);
        ActBean balanceBean = new ActBean(balance);
        balanceBean.addNodeRelationship("items", adjustment);
        service.save(adjustment); // NOTE that this will trigger TillBalanceRules.addToTill(), but will have no effect
        TillHelper.updateBalance(balanceBean, service);
    }
}

From source file:es.tid.fiware.rss.expenditureLimit.processing.ProcessingLimitService.java

/**
 * Check amounts and generate exceptions.
 * //from   w w  w  . ja  v a 2  s  . c o m
 * @param total
 * @param limit
 * @param tx
 * @throws RSSException
 */
private void checkMaxAmountExceed(BigDecimal total, DbeExpendLimit limit, DbeTransaction tx)
        throws RSSException {
    // check that the limit is not exceed
    if (total.compareTo(limit.getFtMaxAmount()) > 0) {
        ProcessingLimitService.logger.error("Credit limit " + limit.getFtMaxAmount() + " exceeded "
                + limit.getId().getTxElType() + " for tx:" + tx.getTxTransactionId());
        String[] args = { "Limit " + limit.getId().getTxElType() + " exceeded by transactionId:"
                + tx.getTxTransactionId() };
        throw new RSSException(UNICAExceptionType.INSUFFICIENT_MOP_BALANCE, args);
    }
}

From source file:com.griddynamics.jagger.engine.e1.scenario.DefaultWorkloadSuggestionMaker.java

@Override
public WorkloadConfiguration suggest(BigDecimal desiredTps, NodeTpsStatistics statistics, int maxThreads) {
    log.debug("Going to suggest workload configuration. desired tps {}. statistics {}", desiredTps, statistics);

    Table<Integer, Integer, Pair<Long, BigDecimal>> threadDelayStats = statistics.getThreadDelayStats();

    if (areEqual(desiredTps, BigDecimal.ZERO)) {
        return WorkloadConfiguration.with(0, 0);
    }/*from  w w w. java2 s  .  c  om*/

    if (threadDelayStats.isEmpty()) {
        throw new IllegalArgumentException("Cannot suggest workload configuration");
    }

    if (!threadDelayStats.contains(CALIBRATION_CONFIGURATION.getThreads(),
            CALIBRATION_CONFIGURATION.getDelay())) {
        log.debug("Statistics is empty. Going to return calibration info.");
        return CALIBRATION_CONFIGURATION;
    }
    if (threadDelayStats.size() == 2 && areEqual(threadDelayStats.get(1, 0).getSecond(), BigDecimal.ZERO)) {
        log.warn("No calibration info. Going to retry.");
        return CALIBRATION_CONFIGURATION;
    }

    Map<Integer, Pair<Long, BigDecimal>> noDelays = threadDelayStats.column(0);

    log.debug("Calculate next thread count");
    Integer threadCount = findClosestPoint(desiredTps, noDelays);

    if (threadCount == 0) {
        threadCount = 1;
    }

    if (threadCount > maxThreads) {
        log.warn("{} calculated max {} allowed", threadCount, maxThreads);
        threadCount = maxThreads;
    }

    int currentThreads = statistics.getCurrentWorkloadConfiguration().getThreads();
    int diff = threadCount - currentThreads;
    if (diff > maxDiff) {
        log.debug("Increasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        return WorkloadConfiguration.with(currentThreads + maxDiff, 0);
    }

    diff = currentThreads - threadCount;
    if (diff > maxDiff) {
        log.debug("Decreasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        if ((currentThreads - maxDiff) > 1) {
            return WorkloadConfiguration.with(currentThreads - maxDiff, 0);
        } else {
            return WorkloadConfiguration.with(1, 0);
        }
    }

    if (!threadDelayStats.contains(threadCount, 0)) {
        return WorkloadConfiguration.with(threadCount, 0);
    }

    // <delay, <timestamp,tps>>
    Map<Integer, Pair<Long, BigDecimal>> delays = threadDelayStats.row(threadCount);

    // not enough statistics to calculate
    if (delays.size() == 1) {
        int delay = 0;
        BigDecimal tpsFromStat = delays.get(0).getSecond();

        // try to guess
        // tpsFromStat can be zero if no statistics was captured till this time
        if ((tpsFromStat.compareTo(BigDecimal.ZERO) > 0) && (desiredTps.compareTo(BigDecimal.ZERO) > 0)) {

            BigDecimal oneSecond = new BigDecimal(TimeUtils.secondsToMillis(1));
            BigDecimal result = oneSecond.multiply(new BigDecimal(threadCount)).divide(desiredTps, 3,
                    BigDecimal.ROUND_HALF_UP);
            result = result.subtract(oneSecond.multiply(new BigDecimal(threadCount)).divide(tpsFromStat, 3,
                    BigDecimal.ROUND_HALF_UP));

            delay = result.intValue();
        }
        // to have some non zero point in statistics
        if (delay == 0) {
            delay = MIN_DELAY;
        }

        delay = checkDelayInRange(delay);
        return WorkloadConfiguration.with(threadCount, delay);
    }

    log.debug("Calculate next delay");
    Integer delay = findClosestPoint(desiredTps, threadDelayStats.row(threadCount));

    delay = checkDelayInRange(delay);
    return WorkloadConfiguration.with(threadCount, delay);

}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFJUInt64Editor.java

public BigDecimal getUInt64Value() {
    final String S_ProcName = "getUInt64Value";
    BigDecimal retval;//from  w  ww  . j  av a 2s  . c om
    String text = getText();
    if ((text == null) || (text.length() <= 0)) {
        retval = null;
    } else {
        if (!super.isEditValid()) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Field is not valid");
        }
        try {
            commitEdit();
        } catch (ParseException e) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Field is not valid - " + e.getMessage(), e);

        }
        Object obj = getValue();
        if (obj == null) {
            retval = null;
        } else if (obj instanceof Short) {
            Short s = (Short) obj;
            BigDecimal v = new BigDecimal(s.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else if (obj instanceof Integer) {
            Integer i = (Integer) obj;
            BigDecimal v = new BigDecimal(i.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else if (obj instanceof Long) {
            Long l = (Long) obj;
            BigDecimal v = new BigDecimal(l.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else if (obj instanceof BigDecimal) {
            BigDecimal v = (BigDecimal) obj;
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else if (obj instanceof Number) {
            Number n = (Number) obj;
            BigDecimal v = new BigDecimal(n.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else {
            throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException(getClass(), S_ProcName,
                    "EditedValue", obj, "Short, Integer, Long, BigDecimal or Number");
        }
    }
    return (retval);
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFJUInt64Editor.java

public void setMinValue(BigDecimal value) {
    final String S_ProcName = "setMinValue";
    if (value == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1, "value");
    }/*ww  w  .  j a va 2  s .c o m*/
    if (value.compareTo(MIN_VALUE) < 0) {
        throw CFLib.getDefaultExceptionFactory().newArgumentUnderflowException(getClass(), S_ProcName, 1,
                "value", value, MIN_VALUE);
    }
    minValue = value;
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFJUInt64Editor.java

public void setMaxValue(BigDecimal value) {
    final String S_ProcName = "setMaxValue";
    if (value == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1, "value");
    }/*from ww  w. j a  v a 2s  .  c o m*/
    if (value.compareTo(MAX_VALUE) > 0) {
        throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, 1,
                "value", value, MAX_VALUE);
    }
    maxValue = value;
}