Example usage for java.math MathContext MathContext

List of usage examples for java.math MathContext MathContext

Introduction

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

Prototype

public MathContext(int setPrecision, RoundingMode setRoundingMode) 

Source Link

Document

Constructs a new MathContext with a specified precision and rounding mode.

Usage

From source file:com.streamsets.pipeline.stage.it.AllSdcTypesIT.java

@Parameterized.Parameters(name = "type({0})")
public static Collection<Object[]> data() throws Exception {
    return Arrays.asList(new Object[][] { { Field.create(Field.Type.BOOLEAN, true), true, Types.BOOLEAN, true },
            { Field.create(Field.Type.CHAR, 'A'), true, Types.VARCHAR, "A" },
            { Field.create(Field.Type.BYTE, (byte) 0x00), false, 0, null },
            { Field.create(Field.Type.SHORT, 10), true, Types.INTEGER, 10 },
            { Field.create(Field.Type.INTEGER, 10), true, Types.INTEGER, 10 },
            { Field.create(Field.Type.LONG, 10), true, Types.BIGINT, 10L },
            { Field.create(Field.Type.FLOAT, 1.5), true, Types.FLOAT, 1.5 },
            { Field.create(Field.Type.DOUBLE, 1.5), true, Types.DOUBLE, 1.5 },
            { Field.create(Field.Type.DATE, new Date(116, 5, 13)), true, Types.DATE, new Date(116, 5, 13) },
            { Field.create(Field.Type.DATETIME, date), true, Types.VARCHAR, datetimeFormat.format(date) },
            { Field.create(Field.Type.TIME, date), true, Types.VARCHAR, timeFormat.format(date) },
            { Field.create(Field.Type.DECIMAL, BigDecimal.valueOf(1.5)), true, Types.DECIMAL,
                    new BigDecimal(BigInteger.valueOf(15), 1, new MathContext(2, RoundingMode.FLOOR)) },
            { Field.create(Field.Type.STRING, "StreamSets"), true, Types.VARCHAR, "StreamSets" },
            { Field.create(Field.Type.BYTE_ARRAY, new byte[] { (byte) 0x00 }), true, Types.BINARY,
                    new byte[] { (byte) 0x00 } },
            { Field.create(Field.Type.MAP, Collections.emptyMap()), false, 0, null },
            { Field.create(Field.Type.LIST, Collections.emptyList()), false, 0, null },
            { Field.create(Field.Type.LIST_MAP, new LinkedHashMap<>()), false, 0, null }, });
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.csv.CSVFileReader.java

private void init() throws IOException {
    doubleMathContext = new MathContext(DIGITS_OF_PRECISION_DOUBLE, RoundingMode.HALF_EVEN);
    firstNumCharSet.addAll(//from w  w w.  j a  v a2  s.c  om
            Arrays.asList(new Character[] { '+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }));
}

From source file:com.xumpy.timesheets.services.implementations.JobsGraphics.java

public OverviewWorkDetails getOverviewWorkDetails(List<Jobs> jobs) throws ParseException {
    MathContext mc = new MathContext(3, RoundingMode.HALF_UP);

    OverviewWorkDetailsSrvPojo overviewWorkDetails = new OverviewWorkDetailsSrvPojo();

    List<WorkingDay> workingDays = calculateWorkingDates(jobs);

    overviewWorkDetails.setHoursToWorkPerDay(new BigDecimal(8)); // Hardcoded

    BigDecimal hoursPayedPerDay = new BigDecimal(0, mc);
    BigDecimal workedWeekHours = new BigDecimal(0, mc);
    BigDecimal workedWeekendHours = new BigDecimal(0, mc);
    BigDecimal weekDays = new BigDecimal(0, mc);
    BigDecimal weekendDays = new BigDecimal(0, mc);
    BigDecimal workedWeekDays = new BigDecimal(0, mc);
    BigDecimal workedWeekendDays = new BigDecimal(0, mc);
    BigDecimal overtimeHours = new BigDecimal(0, mc);
    BigDecimal overtimeDays = new BigDecimal(0, mc);

    for (WorkingDay workingDay : workingDays) {
        if (CustomDateUtils.isWeekDay(workingDay.getDate())) {
            weekDays = weekDays.add(new BigDecimal(1));
            workedWeekHours = workedWeekHours.add(workingDay.getActualWorkHours(), mc);
            workedWeekDays = workedWeekDays.add(new BigDecimal(1));
        } else {//w w w. j a  v a 2 s.c  o m
            weekendDays = weekendDays.add(new BigDecimal(1));
            workedWeekendHours = workedWeekendHours.add(workingDay.getActualWorkHours(), mc);
            workedWeekendDays = workedWeekendDays.add(new BigDecimal(1));
        }

        overtimeHours = overtimeHours.add(workingDay.getOvertimeHours(), mc);

        for (Jobs jobPerDay : workingDay.getJobs()) {
            if (jobPerDay.getJobsGroup().getCompany() != null) {
                if (hoursPayedPerDay
                        .compareTo(jobPerDay.getJobsGroup().getCompany().getDailyPayedHours()) < 0) {
                    hoursPayedPerDay = jobPerDay.getJobsGroup().getCompany().getDailyPayedHours();
                }
            }
        }

        if (!hoursPayedPerDay.equals(new BigDecimal(0))) {
            overtimeDays = overtimeHours.divide(hoursPayedPerDay, mc);
        } else {
            overtimeDays = workedWeekDays.add(workedWeekendDays);
        }
    }

    overviewWorkDetails.setHoursPayedPerDay(hoursPayedPerDay);

    overviewWorkDetails.setWorkedWeekHours(workedWeekHours);
    overviewWorkDetails.setWorkedWeekendHours(workedWeekendHours);
    overviewWorkDetails.setWeekDays(weekDays);
    overviewWorkDetails.setWeekendDays(weekendDays);

    overviewWorkDetails.setWorkedWeekDays(workedWeekDays);
    overviewWorkDetails.setWorkedWeekendDays(workedWeekendDays);

    overviewWorkDetails.setOvertimeHours(overtimeHours);
    overviewWorkDetails.setOvertimeDays(overtimeDays);

    return overviewWorkDetails;
}

From source file:py.una.pol.karaku.math.MathContextProvider.java

/**
 * Contexto a ser utilizado para realizar operaciones.
 *
 * <p>//from  w ww.  j ava2 s  .c  om
 * Retorna un {@link MathContext} que debe ser utilizado para realizar
 * operaciones matemticas. Este contexto tiene la precisin definida por
 * {@link #getPrecision()} y el modo de redondeo definido por
 * {@link #getRoundingMode()}.
 * </p>
 *
 *
 * @return {@link MathContext} inicializado,
 */
public MathContext getContext() {

    if (mathContext == null) {
        mathContext = new MathContext(getPrecision(), getRoundingMode());
    }

    return mathContext;
}

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  a va2s.  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.libreplan.business.test.orders.entities.OrderElementTest.java

private Division division(int numberOfDecimals) {
    return new Division(new MathContext(numberOfDecimals, RoundingMode.HALF_UP));
}

From source file:org.renjin.primitives.MathGroup.java

@Deferrable
@Builtin//from w  w w .  ja v a2 s .  c o m
@DataParallel(value = PreserveAttributeStyle.ALL, passNA = true)
public static double signif(double x, int digits) {
    if (Double.isInfinite(x) || Double.isNaN(x)) {
        return x;
    }
    if (digits <= 0) {
        digits = 1;
    }
    return new BigDecimal(x).round(new MathContext(digits, RoundingMode.HALF_UP)).doubleValue();
}

From source file:org.openhab.binding.plex.internal.PlexConnector.java

private String getProgressCommand(PlexBindingConfig config, Command command) {
    PlexSession session = getSessionByMachineId(config.getMachineIdentifier());
    String url = null;//ww  w.ja va  2s.  c  o  m

    if (session != null) {
        int offset = 0;

        if (command.getClass().equals(PercentType.class)) {
            PercentType percent = (PercentType) command;
            offset = new BigDecimal(session.getDuration()).multiply(percent.toBigDecimal()
                    .divide(new BigDecimal("100"), new MathContext(5, RoundingMode.HALF_UP))).intValue();

            offset = Math.max(0, offset);
            offset = Math.min(session.getDuration(), offset);

            url = String.format("playback/seekTo?offset=%d", offset);
        } else if (command.getClass().equals(IncreaseDecreaseType.class)) {
            if (command.equals(IncreaseDecreaseType.DECREASE))
                url = PlexBindingConstants.PROPERTY_STEP_BACK;
            else
                url = PlexBindingConstants.PROPERTY_STEP_FORWARD;
        }
    }

    return url;
}

From source file:com.gst.portfolio.shareaccounts.domain.ShareAccountCharge.java

private BigDecimal percentageOf(final BigDecimal value, final BigDecimal percentage) {
    BigDecimal percentageOf = BigDecimal.ZERO;
    if (isGreaterThanZero(value)) {
        final MathContext mc = new MathContext(8, MoneyHelper.getRoundingMode());
        final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc);
        percentageOf = value.multiply(multiplicand, mc);
    }//from   w w  w  .jav  a2  s  .  c  om
    return percentageOf;
}

From source file:com.ufnet.ws.service.UserService.java

/**
 * cardDelUser/*from   www.ja v  a  2s  .com*/
 * @param request
 * @return
 */
public int cardDelUser(CardDelUserRequest request) {
    // Request && Validation
    String userId = request.getUserId();
    if (StringUtils.isBlank(userId)) {
        log.error("userid[" + userId + "] is blank.");
        return -1;
    }
    // Process
    int returnCode = -1;
    try {
        // ?
        UserInfo userInfo = userInfoRepository.select(userId);
        if (userInfo != null) {
            returnCode = new BigDecimal(userInfo.getAvailableAmount(), new MathContext(0, RoundingMode.FLOOR))
                    .toBigInteger().intValue();
            // 
            userInfoRepository.delete(userId);
            userIpMacRepository.delete(userInfo.getAccountId());
        } else {
            log.error("userid[" + userId + "] not exists.");
            return -1;
        }
    } catch (Exception e) {
        log.error(ExceptionUtils.getStackTrace(e));
    }
    return returnCode;
}