Example usage for java.math RoundingMode CEILING

List of usage examples for java.math RoundingMode CEILING

Introduction

In this page you can find the example usage for java.math RoundingMode CEILING.

Prototype

RoundingMode CEILING

To view the source code for java.math RoundingMode CEILING.

Click Source Link

Document

Rounding mode to round towards positive infinity.

Usage

From source file:com.vuw.project1.riverwatch.colour_algorithm.InfoFragment.java

public void setNitrateNitrite(Bundle result) {
    Double nitrate = result.getDouble("nitrate");
    Double nitrite = result.getDouble("nitrite");
    // set text views to nitrite and nitrate levels
    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.CEILING);
    nitrateTextView.setText("Nitrate: " + df.format(nitrate));
    nitriteTextView.setText("Nitrite: " + df.format(nitrite));
}

From source file:org.jmxtrans.samples.graphite.GraphiteDataInjector.java

public void generateLoad() throws Exception {
    System.out.println("Inject data on Graphite server " + this.graphiteHost);

    TimeSeries timeSeries = new TimeSeries("shopping-cart.raw");

    DateTime now = new DateTime();
    DateTime end = now.plusDays(1);/*from  w  w w . j av  a2s. c o m*/

    DateTime date = now.minusDays(15);
    DateTime twoDaysAfterBegin = date.plusDays(2);

    int integratedValue = 0;

    MathContext mathContext = new MathContext(1, RoundingMode.CEILING);

    int randomFactor = 0;

    while (date.isBefore(end)) {
        if (timeSeries.getItemCount() % 120 == 0) {
            randomFactor = 10 + random.nextInt(2);
        }
        int weekGrowthFactor = 6 - (now.getWeekOfWeekyear() - date.getWeekOfWeekyear());
        int value = new BigDecimal(randomFactor) // random factor
                .multiply(new BigDecimal(10)) // go to cents of USD
                .multiply(new BigDecimal(weekGrowthFactor))
                .multiply(new BigDecimal(hourlyDistribution[date.getHourOfDay()]))
                .multiply(new BigDecimal(weeklyDistribution[date.getDayOfWeek()]))
                .divide(new BigDecimal(20), mathContext).intValue(); // split hourly value in minutes

        integratedValue += value;
        for (int i1 = 0; i1 < 3; i1++) {
            timeSeries.add(new Minute(date.toDate()), integratedValue);
            date = date.plusMinutes(1);
        }
    }

    TimeSeries ordersPriceInCentsTimeSeries = MovingAverage.createMovingAverage(timeSeries,
            "shopping-cart.OrdersPriceInCents", 60 * 7, 0);

    TimeSeries ordersPriceInCentsSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrdersPriceInCents");
    TimeSeries ordersPriceInCentsSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrdersPriceInCents");
    int resetValue2ToZeroOffset = 0; // reset value 2 after 3 days of metrics
    for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) {
        TimeSeriesDataItem dataItem = ordersPriceInCentsTimeSeries.getDataItem(i);
        int value = dataItem.getValue().intValue();
        // value1 is 5% higher to value2 due to a 'weirdness' in the load balancing
        int value1 = Math.min((int) (value * 1.05 / 2), value);

        {
            // simulate srv2 restart
            DateTime currentDate = new DateTime(dataItem.getPeriod().getStart());
            boolean shouldResetValue2 = resetValue2ToZeroOffset == 0
                    && currentDate.getDayOfYear() == twoDaysAfterBegin.getDayOfYear();
            if (shouldResetValue2) {
                resetValue2ToZeroOffset = value - value1;
                System.out.println("reset value2 of " + resetValue2ToZeroOffset + " at " + currentDate);
            }
        }

        int value2 = value - value1 - resetValue2ToZeroOffset;
        // System.out.println("value=" + value + ", value1=" + value1 + ", value2=" + value2);
        ordersPriceInCentsSrv1TimeSeries.add(dataItem.getPeriod(), value1);
        ordersPriceInCentsSrv2TimeSeries.add(dataItem.getPeriod(), value2);
    }

    TimeSeries orderItemsCountTimeSeries = new TimeSeries("shopping-cart.OrderItemsCount");
    TimeSeries orderItemsCountSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrderItemsCount");
    TimeSeries orderItemsCountSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrderItemsCount");

    for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) {
        RegularTimePeriod period = ordersPriceInCentsTimeSeries.getDataItem(i).getPeriod();
        int ordersPriceInCents1 = ordersPriceInCentsSrv1TimeSeries.getDataItem(i).getValue().intValue();
        int ordersPriceInCents2 = ordersPriceInCentsSrv2TimeSeries.getDataItem(i).getValue().intValue();

        int value1 = ordersPriceInCents1 / 600;
        int value2 = ordersPriceInCents2 / 600;

        orderItemsCountTimeSeries.add(period, value1 + value2);
        orderItemsCountSrv1TimeSeries.add(period, value1);
        orderItemsCountSrv2TimeSeries.add(period, value2);

    }

    exportMetrics(ordersPriceInCentsTimeSeries, ordersPriceInCentsSrv1TimeSeries,
            ordersPriceInCentsSrv2TimeSeries, ordersPriceInCentsTimeSeries, orderItemsCountTimeSeries,
            orderItemsCountSrv1TimeSeries, orderItemsCountSrv2TimeSeries);

    TimeSeries activeSrv1Visitors = new TimeSeries("srv1.visitors.currentActive");
    TimeSeries activeSrv2Visitors = new TimeSeries("srv1.visitors.currentActive");

}

From source file:org.egov.ptis.repository.dashboard.RevenueDashboardRepository.java

public List<Map<String, Object>> getRevenueZonewisePerformance() {
    final List<Object[]> overallData = getQuery("revenue.ptis.zonewise.overall.performance").list();
    final Map<String, Map<String, Object>> revenueDataHolder = new HashMap<String, Map<String, Object>>();
    for (final Object[] revenueObj : overallData) {
        final Map<String, Object> revnData = new HashMap<String, Object>();
        revnData.put("zone", String.valueOf(revenueObj[0]));
        final BigDecimal collectionPerc = (BigDecimal) revenueObj[1];
        revnData.put("collectionPerc", collectionPerc != null ? collectionPerc.doubleValue() : "0");
        revenueDataHolder.put(String.valueOf(revenueObj[0]), revnData);
    }/*from   w ww. j  a  va 2 s.  c o m*/

    final List<Object[]> monthlyData = getQuery("revenue.ptis.zonewise.monthly.performance").list();
    for (final Object[] revenuData : monthlyData) {
        final Map<String, Object> revnData = revenueDataHolder.get(String.valueOf(revenuData[0]));
        final BigDecimal amtTargeted = (BigDecimal) revenuData[1];
        revnData.put("amtTargeted", amtTargeted != null ? amtTargeted.doubleValue() : "0");
        final BigDecimal amt_collectd = (BigDecimal) revenuData[2];
        revnData.put("amt_collectd", amt_collectd != null ? amt_collectd.doubleValue() : "0");
        final BigDecimal percCollections = (BigDecimal) revenuData[3];
        revnData.put("percCollections",
                percCollections != null ? percCollections.setScale(2, RoundingMode.CEILING).doubleValue()
                        : "0");
    }

    final List<Map<String, Object>> revenueAggrData = new ArrayList<Map<String, Object>>(
            revenueDataHolder.values());
    // SORT BY ZONEWISE MONTHLY COLLECTION %
    sortData(revenueAggrData, "percCollections");

    // ASSIGN MONTHLY RANK BASED ON SORT ORDER
    assignRank(revenueAggrData, "rank");

    // SORT BY ZONEWISE OVERALL COLLECTION %
    sortData(revenueAggrData, "collectionPerc");

    // ASSIGN OVERALL RANK BASED ON SORT ORDER
    assignRank(revenueAggrData, "overallrank");

    return revenueAggrData;
}

From source file:com.github.rinde.rinsim.examples.demo.factory.AgvModel.java

@Override
public void handleEvent(Event e) {
    verify(e instanceof PDPModelEvent);
    final PDPModelEvent event = (PDPModelEvent) e;
    final Box box = (Box) verifyNotNull(event.parcel);
    if (e.getEventType() == PDPModelEventType.END_PICKUP) {
        occupiedPositions.remove(box.getPickupLocation());
    }/*w  ww  .  ja v  a 2 s  . c  o m*/
    if (e.getEventType() == PDPModelEventType.END_DELIVERY) {
        final long duration = DoubleMath.roundToLong(
                FactoryExample.SERVICE_DURATION / 2d + rng.nextDouble() * FactoryExample.SERVICE_DURATION,
                RoundingMode.CEILING);
        simulator.get().unregister(box);

        final BoxHandle bh = box.boxHandle;
        bh.wordIndex = (bh.wordIndex + 1) % points.size();

        Point dest;
        if (bh.index >= points.get(bh.wordIndex).size()) {
            dest = rndBorder();
        } else {
            dest = points.get(bh.wordIndex).get(bh.index);
            occupiedPositions.add(dest);
        }

        final Box newBox = new Box(box.getDeliveryLocation(), dest, duration, bh);
        bh.box = newBox;

        simulator.get().register(newBox);
    }
}

From source file:org.mifos.config.AccountingRulesIntegrationTest.java

@Test
public void testGetFinalRoundingMode() {
    RoundingMode configuredMode = AccountingRules.getFinalRoundingMode();
    String roundingMode = "CEILING";
    RoundingMode configRoundingMode = RoundingMode.CEILING;
    ConfigurationManager configMgr = ConfigurationManager.getInstance();
    configMgr.setProperty(AccountingRulesConstants.FINAL_ROUNDING_MODE, roundingMode);
    // return value from accounting rules class has to be the value defined
    // in the config file
    Assert.assertEquals(configRoundingMode, AccountingRules.getFinalRoundingMode());
    // clear the RoundingRule property from the config file
    configMgr.clearProperty(AccountingRulesConstants.FINAL_ROUNDING_MODE);
    RoundingMode defaultValue = AccountingRules.getFinalRoundingMode();
    Assert.assertEquals(defaultValue, RoundingMode.CEILING);
    // now set a wrong rounding mode in config
    roundingMode = "DOWN";
    configMgr.addProperty(AccountingRulesConstants.FINAL_ROUNDING_MODE, roundingMode);
    try {//from  w w  w .  ja  v  a 2 s .c  o m
        AccountingRules.getFinalRoundingMode();
    } catch (RuntimeException e) {
        Assert.assertEquals(e.getMessage(),
                "FinalRoundingMode defined in the config file is not CEILING, FLOOR, HALF_UP. It is "
                        + roundingMode);
    }
    // save it back
    configMgr.setProperty(AccountingRulesConstants.FINAL_ROUNDING_MODE, configuredMode.toString());

}

From source file:gobblin.salesforce.SalesforceSource.java

String generateSpecifiedPartitions(Histogram histogram, int maxPartitions, long expectedHighWatermark) {
    long interval = DoubleMath.roundToLong((double) histogram.totalRecordCount / maxPartitions,
            RoundingMode.CEILING);
    int totalGroups = histogram.getGroups().size();

    log.info("Histogram total record count: " + histogram.totalRecordCount);
    log.info("Histogram total groups: " + totalGroups);
    log.info("maxPartitions: " + maxPartitions);
    log.info("interval: " + interval);

    List<HistogramGroup> groups = histogram.getGroups();
    List<String> partitionPoints = new ArrayList<>();
    DescriptiveStatistics statistics = new DescriptiveStatistics();

    int count = 0;
    HistogramGroup group;/*from www  .  ja v a  2s. co  m*/
    Iterator<HistogramGroup> it = groups.iterator();
    while (it.hasNext()) {
        group = it.next();
        if (count == 0) {
            // Add a new partition point;
            partitionPoints
                    .add(Utils.toDateTimeFormat(group.getKey(), DAY_FORMAT, Partitioner.WATERMARKTIMEFORMAT));
        }

        // Move the candidate to a new bucket if the attempted total is 2x of interval
        if (count != 0 && count + group.count >= 2 * interval) {
            // Summarize current group
            statistics.addValue(count);
            // A step-in start
            partitionPoints
                    .add(Utils.toDateTimeFormat(group.getKey(), DAY_FORMAT, Partitioner.WATERMARKTIMEFORMAT));
            count = group.count;
        } else {
            // Add group into current partition
            count += group.count;
        }

        if (count >= interval) {
            // Summarize current group
            statistics.addValue(count);
            // A fresh start next time
            count = 0;
        }
    }

    // If the last group is used as the last partition point
    if (count == 0) {
        // Exchange the last partition point with global high watermark
        partitionPoints.set(partitionPoints.size() - 1, Long.toString(expectedHighWatermark));
    } else {
        // Summarize last group
        statistics.addValue(count);
        // Add global high watermark as last point
        partitionPoints.add(Long.toString(expectedHighWatermark));
    }

    log.info("Dynamic partitioning statistics: ");
    log.info("data: " + Arrays.toString(statistics.getValues()));
    log.info(statistics.toString());
    String specifiedPartitions = Joiner.on(",").join(partitionPoints);
    log.info("Calculated specified partitions: " + specifiedPartitions);
    return specifiedPartitions;
}

From source file:com.github.rinde.rinsim.examples.demo.factory.FactoryExample.java

static Graph<?> createGraph(ImmutableList<ImmutableList<Point>> points) {
    int max = 0;/*from   w  ww  .  j  a v  a 2s .  c o  m*/
    double xMax = 0;
    double yMax = 0;
    for (final List<Point> ps : points) {
        max = Math.max(max, ps.size());
        for (final Point p : ps) {
            xMax = Math.max(p.x, xMax);
            yMax = Math.max(p.y, yMax);
        }
    }

    int width = DoubleMath.roundToInt(xMax / SPACING, RoundingMode.CEILING);
    width += VERTICAL_LINE_SPACING - width % VERTICAL_LINE_SPACING;
    width += width / VERTICAL_LINE_SPACING % 2 == 0 ? VERTICAL_LINE_SPACING : 0;

    int height = DoubleMath.roundToInt(yMax / SPACING, RoundingMode.CEILING) + 2;
    height += height % 2;
    return createGrid(width, height, 1, VERTICAL_LINE_SPACING, SPACING);
}

From source file:org.yes.cart.payment.impl.PayPalProPaymentGatewayImpl.java

private NvpBuilder createAuthRequest(final Payment payment, final String paymentAction) {
    final NvpBuilder npvs = new NvpBuilder();
    npvs.addRaw("PAYMENTACTION", paymentAction);
    npvs.addRaw("INVNUM", payment.getOrderShipment());
    npvs.addRaw("CREDITCARDTYPE", payment.getCardType());
    npvs.addRaw("ACCT", payment.getCardNumber());
    npvs.addRaw("EXPDATE", payment.getCardExpireMonth() + payment.getCardExpireYear());
    npvs.addRaw("CVV2", payment.getCardCvv2Code());

    npvs.addRaw("AMT", payment.getPaymentAmount().setScale(2, RoundingMode.HALF_UP).toString());
    npvs.addRaw("CURRENCYCODE", payment.getOrderCurrency());

    int i = 0;//from w w w.ja v a  2 s  .c o  m

    BigDecimal itemsNetTotal = Total.ZERO;
    BigDecimal ship = Total.ZERO;

    for (final PaymentLine item : payment.getOrderItems()) {

        if (item.isShipment()) {

            ship = item.getUnitPrice();

        } else {

            final BigDecimal intQty = item.getQuantity().setScale(0, RoundingMode.CEILING);

            final String skuName;
            final BigDecimal qty;
            if (MoneyUtils.isFirstEqualToSecond(intQty, item.getQuantity())) {
                // integer qty
                skuName = item.getSkuName();
                qty = intQty.stripTrailingZeros();
            } else {
                // fractional qty
                skuName = item.getQuantity().toPlainString().concat("x ").concat(item.getSkuName());
                qty = BigDecimal.ONE;
            }

            npvs.addEncoded("L_NUMBER" + i,
                    item.getSkuCode().length() > ITEMSKU ? item.getSkuCode().substring(0, ITEMSKU - 1) + "~"
                            : item.getSkuCode());
            npvs.addEncoded("L_NAME" + i,
                    skuName.length() > ITEMNAME ? skuName.substring(0, ITEMNAME - 1) + "~" : skuName);

            npvs.addRaw("L_QTY" + i, qty.stripTrailingZeros().toPlainString());

            final BigDecimal itemNetAmount = item.getUnitPrice().multiply(item.getQuantity())
                    .subtract(item.getTaxAmount()).setScale(Total.ZERO.scale(), RoundingMode.HALF_UP);
            final BigDecimal itemNetPricePerAdjustedQty = itemNetAmount.divide(qty, Total.ZERO.scale(),
                    BigDecimal.ROUND_HALF_UP);
            // Need to do this to overcome rounding
            final BigDecimal restoredNetAmount = itemNetPricePerAdjustedQty.multiply(qty)
                    .setScale(Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP);

            itemsNetTotal = itemsNetTotal.add(restoredNetAmount);
            //                final BigDecimal taxUnit = MoneyUtils.isFirstBiggerThanSecond(item.getTaxAmount(), Total.ZERO) ? item.getTaxAmount().divide(qty, Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP) : Total.ZERO;

            npvs.addRaw("L_AMT" + i, itemNetPricePerAdjustedQty.toPlainString());

            //                npvs.addRaw("L_TAXAMT" + i, taxUnit.toPlainString());

            i++;
        }
    }

    final BigDecimal itemsAndShipping = itemsNetTotal.add(ship);
    final BigDecimal paymentNet = payment.getPaymentAmount().subtract(payment.getTaxAmount());
    if (MoneyUtils.isFirstBiggerThanSecond(itemsAndShipping, paymentNet)) {

        npvs.addRaw("SHIPDISCAMT", paymentNet.subtract(itemsAndShipping).toPlainString());

    }

    npvs.addRaw("ITEMAMT", itemsNetTotal.toPlainString());
    npvs.addRaw("SHIPPINGAMT", ship.toPlainString());
    npvs.addRaw("TAXAMT", payment.getTaxAmount().toPlainString());

    if (payment.getBillingAddress() != null) {
        npvs.addEncoded("EMAIL", payment.getBillingEmail());
        npvs.addEncoded("FIRSTNAME", payment.getBillingAddress().getFirstname());
        npvs.addEncoded("LASTNAME", payment.getBillingAddress().getLastname());
        npvs.addEncoded("STREET", payment.getBillingAddress().getAddrline1());
        if (StringUtils.isNotBlank(payment.getBillingAddress().getAddrline2())) {
            npvs.addEncoded("STREET2", payment.getBillingAddress().getAddrline2());
        }
        npvs.addEncoded("CITY", payment.getBillingAddress().getCity());
        npvs.addEncoded("STATE", payment.getBillingAddress().getStateCode());
        npvs.addEncoded("ZIP", payment.getBillingAddress().getStateCode());
        npvs.addEncoded("COUNTRYCODE", payment.getBillingAddress().getCountryCode());
    }

    if (payment.getShippingAddress() != null) {
        npvs.addEncoded("SHIPTONAME",
                payment.getShippingAddress().getFirstname() + " " + payment.getShippingAddress().getLastname());
        npvs.addEncoded("SHIPTOSTREET", payment.getShippingAddress().getAddrline1());
        if (StringUtils.isNotBlank(payment.getShippingAddress().getAddrline2())) {
            npvs.addEncoded("SHIPTOSTREET2", payment.getShippingAddress().getAddrline2());
        }
        npvs.addEncoded("SHIPTOCITY", payment.getShippingAddress().getCity());
        npvs.addEncoded("SHIPTOSTATE", payment.getShippingAddress().getStateCode());
        npvs.addEncoded("SHIPTOZIP", payment.getShippingAddress().getStateCode());
        npvs.addEncoded("SHIPTOCOUNTRY", payment.getShippingAddress().getCountryCode());
    }

    return npvs;
}

From source file:org.apache.pdfbox.rendering.TilingPaint.java

/**
 * Returns the closest integer which is larger than the given number.
 * Uses BigDecimal to avoid floating point error which would cause gaps in the tiling.
 *//*  www  .jav a2 s .  c om*/
private static int ceiling(double num) {
    BigDecimal decimal = new BigDecimal(num);
    decimal = decimal.setScale(5, RoundingMode.CEILING); // 5 decimal places of accuracy
    return decimal.intValue();
}

From source file:easycare.load.util.db.loader.UserDataLoader.java

private void createUsersWithSubsetLocations(ContextOfCurrentLoad context, Organisation organisation,
        String organisationNumber) {
    List<Location> locations = organisation.activeLocations();
    BigDecimal totalLocations = BigDecimal.valueOf(locations.size());
    BigDecimal twoThirdLocations = totalLocations
            .divide(BigDecimal.valueOf(_THREE), _SIX, RoundingMode.HALF_EVEN).multiply(BigDecimal.valueOf(2))
            .setScale(0, RoundingMode.CEILING);
    Location[] locationsToAdd = locations.subList(0, twoThirdLocations.intValue()).toArray(new Location[0]);
    List<Role> roles = newArrayList(seedData.getRole(ROLE_CLINICIAN));
    buildUser(context, "remy" + organisationNumber, "Remy", "Roam", organisation, roles, organisationNumber,
            locationsToAdd);/*  ww w .  j  a  v a  2  s  .c  o m*/
}