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:net.lizalab.util.RdRandRandomTest.java

/**
 * Runs the Monte Carlo Pi approximation test for the specified
 * instance of Random.//from w  ww . j  av a2s. c  o  m
 * @param random The RNG instance to test.
 * @param doAssert Flag to indicate whether result should be asserted or simply logged.
 */
private void monteCarloPiTest(Random random, boolean doAssert) {
    final String methodName = "monteCarloPiTest : ";

    int inRandCircle = 0;

    // xr and yr will be the random point
    // zr will be the calculated distance to the center
    double xr, yr, zr;

    long start = System.currentTimeMillis();
    for (int i = 0; i < numPoints; i++) {
        xr = random.nextDouble();
        yr = random.nextDouble();

        zr = (xr * xr) + (yr * yr);
        if (zr <= 1.0) {
            inRandCircle++;
        }
    }
    long end = System.currentTimeMillis();
    LOGGER.info("{} Time: {}ms", methodName, end - start);

    // calculate the Pi approximations
    double randomPi = (double) inRandCircle / numPoints * 4.0;

    // calculate the difference and % error
    double diff = (randomPi - Math.PI);
    double randomError = diff / Math.PI * 100;
    LOGGER.info("{} Pi Approximation: {}, Diff: {}, Error %: {}", methodName, randomPi, diff, randomError);
    BigDecimal randomPiBD = new BigDecimal(randomPi);
    randomPiBD = randomPiBD.setScale(precision - 1, RoundingMode.DOWN);
    // Verify result.
    boolean result = randomPiBD.compareTo(pi) == 0;
    String msg = "Pi approximation not sufficiently precise for " + random.getClass();
    if (doAssert) {
        assertTrue(msg, result);
    } else {
        if (!result) {
            LOGGER.warn("{} {}", methodName, msg);
        }
    }
}

From source file:org.openvpms.archetype.tools.account.AccountBalanceTool.java

/**
 * Checks the account balance for the specified customer.
 *
 * @param customer the customer/*from w  w w . j a va2 s.  c o m*/
 * @return <tt>true</tt> if the account balance is correct,
 *         otherwise <tt>false</tt>
 */
public boolean check(Party customer) {
    log.info("Checking account balance for " + customer.getName() + ", ID=" + customer.getId());
    BalanceCalculator calc = new BalanceCalculator(service);
    boolean result = false;
    try {
        BigDecimal expected = calc.getDefinitiveBalance(customer);
        BigDecimal actual = calc.getBalance(customer);
        result = expected.compareTo(actual) == 0;
        if (!result) {
            log.error("Failed to check account balance for " + customer.getName() + ", ID=" + customer.getId()
                    + ": expected balance=" + expected + ", actual balance=" + actual);
        }
    } catch (CustomerAccountRuleException exception) {
        // thrown when an opening or closing balance doesn't match
        log.error("Failed to check account balance for " + customer.getName() + ", ID=" + customer.getId()
                + ": " + exception.getMessage());
    }
    return result;
}

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

@Override
@NotOnUpdate//w  w w .j a  v a  2s . co m
public TBuilder setShippingCostsAmount(BigDecimal amount) {
    BillyValidator.notNull(amount,
            GenericInvoiceEntryBuilderImpl.LOCALIZER.getString("field.shipping_costs_amount"));
    Validate.isTrue(amount.compareTo(BigDecimal.ZERO) >= 0);
    this.getTypeInstance().setShippingCostsAmount(amount);
    return this.getBuilder();
}

From source file:org.openvpms.archetype.rules.finance.account.CustomerBalanceGeneratorTestCase.java

/**
 * Determines if the balance as returned by
 * {@link BalanceCalculator#getBalance} matches that returned by
 * {@link BalanceCalculator#getDefinitiveBalance}.
 *
 * @param customer the customer//from ww w. j  a v  a 2 s .  c  om
 * @return <tt>true</tt> if the balances match, otherwise <tt>false</tt>
 */
private boolean checkBalance(Party customer) {
    BalanceCalculator calc = new BalanceCalculator(getArchetypeService());
    BigDecimal expected = calc.getDefinitiveBalance(customer);
    BigDecimal actual = calc.getBalance(customer);
    return expected.compareTo(actual) == 0;
}

From source file:com.qcadoo.mes.masterOrders.hooks.MasterOrderDetailsHooks.java

public void showErrorWhenCumulatedQuantity(final ViewDefinitionState view) {
    FormComponent form = (FormComponent) view.getComponentByReference(L_FORM);
    Entity masterOrder = form.getEntity();

    if (masterOrder == null) {
        return;/*from   ww w. ja va2s  . c o  m*/
    }

    if (!masterOrder.getStringField(MasterOrderFields.MASTER_ORDER_TYPE)
            .equals(MasterOrderType.ONE_PRODUCT.getStringValue())) {
        return;
    }

    BigDecimal cumulatedQuantity = masterOrder.getDecimalField(CUMULATED_ORDER_QUANTITY);
    BigDecimal masterQuantity = masterOrder.getDecimalField(MASTER_ORDER_QUANTITY);

    if (cumulatedQuantity != null && masterQuantity != null
            && cumulatedQuantity.compareTo(masterQuantity) == -1) {
        form.addMessage("masterOrders.masterOrder.masterOrderCumulatedQuantityField.wrongQuantity",
                MessageType.INFO, false);
    }
}

From source file:com.envision.envservice.service.RankingListService.java

private List<SpiritSortBo> sortuserPraiseNumSort(Map<String, Integer> lowerUserPraiseNum,
        final SortType sortType) {
    List<SpiritSortBo> sbos = new ArrayList<SpiritSortBo>();

    for (Entry<String, Integer> entry : lowerUserPraiseNum.entrySet()) {
        if (!TOTAL.equals(entry.getKey())) {
            SpiritSortBo sbo = new SpiritSortBo();
            sbo.setUserId(entry.getKey());
            BigDecimal fz = new BigDecimal(entry.getValue());
            BigDecimal fm = new BigDecimal(lowerUserPraiseNum.get(TOTAL));
            if (fm.intValue() == 0) {
                sbo.setPercent("0");
            } else {
                DecimalFormat df = new DecimalFormat("0.00");
                String pe = df.format(fz.multiply(new BigDecimal(100)).divide(fm, 2, RoundingMode.HALF_UP));
                sbo.setPercent(pe);/* ww  w.jav a 2 s .c  o  m*/
            }
            sbos.add(sbo);
        }
    }
    // ?
    // Collections.sort(sbos, new SpiritSortBoComparator(sortType));
    Collections.sort(sbos, new Comparator<SpiritSortBo>() {

        public int compare(SpiritSortBo o1, SpiritSortBo o2) {
            BigDecimal o1Percent = new BigDecimal(o1.getPercent());
            BigDecimal o2Percent = new BigDecimal(o2.getPercent());

            int multiplier = -1;
            if (sortType.equals(SortType.ASC)) {
                multiplier = 1;
            }
            return o1Percent.compareTo(o2Percent) * multiplier;
        }

    });
    return sbos;
}

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

/**
 * Check that the limits are updated.//  w w w  . j  av  a2  s .  co m
 */
@Test
public void updateControls() {
    try {
        DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
        // Set user for testing
        tx.setTxEndUserId("userIdUpdate");
        tx.setFtChargedTotalAmount(new BigDecimal(2));
        List<DbeExpendControl> controls = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        // Reset dates to current date--> if not test fail
        updateDate(controls);
        limitService.updateLimit(tx);
        List<DbeExpendControl> controls2 = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        for (DbeExpendControl control : controls) {
            if (controls2.get(0).getId().getTxElType().equalsIgnoreCase(control.getId().getTxElType())) {
                BigDecimal total = control.getFtExpensedAmount().add(tx.getFtChargedTotalAmount());
                Assert.assertTrue(total.compareTo(controls2.get(0).getFtExpensedAmount()) == 0);
            }
        }
    } catch (RSSException e) {
        Assert.fail("Exception not expected" + e.getMessage());
    }
}

From source file:nl.strohalm.cyclos.utils.conversion.NumberConverter.java

public String toString(final T number) {
    if (number == null) {
        return null;
    }/*from  w  ww  .  j  ava  2s . c om*/
    BigDecimal bigDecimal = CoercionHelper.coerce(BigDecimal.class, number);

    // Convert to negative if on negativeToAbsoluteValue mode and number is not zero
    if (negativeToAbsoluteValue) {
        bigDecimal = bigDecimal.abs();
    }

    // For very small negative numbers, like 0.000001, avoid formatting as -0,00
    final BigDecimal delta = getDelta();
    if (bigDecimal.compareTo(BigDecimal.ZERO) < 0 && bigDecimal.compareTo(delta) > 0) {
        bigDecimal = BigDecimal.ZERO;
    }

    return numberFormat.format(bigDecimal);
}

From source file:com.brq.wallet.external.cashila.activity.CashilaNewFragment.java

boolean amountIsWithinLimits() {
    final BigDecimal amount = getAmount();
    return (amount != null && currentAccountLimits != null) && !(amount.compareTo(currentAccountLimits.max) > 0
            || amount.compareTo(currentAccountLimits.min) < 0);
}

From source file:it.newfammulfin.api.EntryResource.java

private <K> boolean checkAndBalanceZeroShares(final Map<K, BigDecimal> shares, BigDecimal expectedSum) {
    if (shares.isEmpty()) {
        return false;
    }/*  www  .  j a v a 2s. c  o  m*/
    boolean equalShares = false;
    if (!Util.containsNotZero(shares.values())) {
        equalShares = true;
        expectedSum = expectedSum.setScale(Math.max(DEFAULT_SHARE_SCALE, expectedSum.scale()));
        for (Map.Entry<K, BigDecimal> shareEntry : shares.entrySet()) {
            shareEntry.setValue(expectedSum.divide(BigDecimal.valueOf(shares.size()), RoundingMode.DOWN));
        }
    }
    K largestKey = shares.keySet().iterator().next();
    for (Map.Entry<K, BigDecimal> share : shares.entrySet()) {
        if (share.getValue().abs().compareTo(shares.get(largestKey).abs()) > 0) {
            largestKey = share.getKey();
        }
    }
    BigDecimal remainder = Util.remainder(shares.values(), expectedSum);
    if (remainder.compareTo(BigDecimal.ZERO) != 0) {
        shares.put(largestKey, shares.get(largestKey).add(remainder));
    }
    return equalShares;
}