Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

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

Prototype

RoundingMode HALF_UP

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

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:org.kuali.coeus.propdev.impl.print.ProposalBaseStream.java

/**
 *
 * This method computes the number of months between any 2 given {@link java.sql.Date} objects
 *
 * @param dateStart starting date.//www  . jav  a 2  s  .  c o  m
 * @param dateEnd end date.
 *
 * @return number of months between the start date and end date.
 */
public ScaleTwoDecimal getNumberOfMonths(Date dateStart, Date dateEnd) {
    ScaleTwoDecimal monthCount = ScaleTwoDecimal.ZERO;
    int fullMonthCount = 0;

    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    startDate.setTime(dateStart);
    endDate.setTime(dateEnd);

    startDate.clear(Calendar.HOUR);
    startDate.clear(Calendar.MINUTE);
    startDate.clear(Calendar.SECOND);
    startDate.clear(Calendar.MILLISECOND);

    endDate.clear(Calendar.HOUR);
    endDate.clear(Calendar.MINUTE);
    endDate.clear(Calendar.SECOND);
    endDate.clear(Calendar.MILLISECOND);

    if (startDate.after(endDate)) {
        return ScaleTwoDecimal.ZERO;
    }
    int startMonthDays = startDate.getActualMaximum(Calendar.DATE) - startDate.get(Calendar.DATE);
    startMonthDays++;
    int startMonthMaxDays = startDate.getActualMaximum(Calendar.DATE);
    BigDecimal startMonthFraction = BigDecimal.valueOf(startMonthDays).setScale(2, RoundingMode.HALF_UP).divide(
            BigDecimal.valueOf(startMonthMaxDays).setScale(2, RoundingMode.HALF_UP), RoundingMode.HALF_UP);

    int endMonthDays = endDate.get(Calendar.DATE);
    int endMonthMaxDays = endDate.getActualMaximum(Calendar.DATE);

    BigDecimal endMonthFraction = BigDecimal.valueOf(endMonthDays).setScale(2, RoundingMode.HALF_UP).divide(
            BigDecimal.valueOf(endMonthMaxDays).setScale(2, RoundingMode.HALF_UP), RoundingMode.HALF_UP);

    startDate.set(Calendar.DATE, 1);
    endDate.set(Calendar.DATE, 1);

    while (startDate.getTimeInMillis() < endDate.getTimeInMillis()) {
        startDate.set(Calendar.MONTH, startDate.get(Calendar.MONTH) + 1);
        fullMonthCount++;
    }
    fullMonthCount = fullMonthCount - 1;
    monthCount = monthCount.add(new ScaleTwoDecimal(fullMonthCount))
            .add(new ScaleTwoDecimal(startMonthFraction)).add(new ScaleTwoDecimal(endMonthFraction));
    return monthCount;
}

From source file:com.github.rinde.rinsim.scenario.generator.PoissonProcessTest.java

/**
 * Tests whether the Poisson process has a Poisson distribution.
 *//*from  w w  w. jav a 2 s  .c o  m*/
@Test
public void testPoissonDistribution() {
    final double length = poisson.getLength();
    final Frequency f = new Frequency();

    final RandomGenerator rng = new MersenneTwister(0);
    for (int i = 0; i < 1000; i++) {

        final List<Double> doubles = poisson.generate(rng.nextLong());
        final List<Long> list = newArrayList();
        for (final double d : doubles) {
            list.add(DoubleMath.roundToLong(d, RoundingMode.HALF_UP));
        }
        ascendingOrderTest(list);
        // add the number of announcements
        f.addValue(list.size());
    }
    final double averageIntensity;
    if (poisson instanceof NonHomogenous && ((NonHomogenous) poisson).lambd instanceof SineIntensity) {
        final SineIntensity si = (SineIntensity) ((NonHomogenous) poisson).lambd;

        final double period = 1d / si.getFrequency();
        final double periods = length / period;
        final double totalEvents = si.area() * periods;
        averageIntensity = totalEvents / length;
    } else {
        averageIntensity = poisson.intensity;
    }
    assertTrue(isPoissonProcess(f, averageIntensity, length, 0.001));
    assertFalse(isPoissonProcess(f, 2, length, 0.01));
    assertFalse(isPoissonProcess(f, 0.1, length, 0.0001));
    assertFalse(isPoissonProcess(f, 15, length, 0.001));
    assertFalse(isPoissonProcess(f, 1000, length, 0.0001));
}

From source file:de.fhg.igd.iva.explorer.main.JStatBar.java

private int mapXToScreen(double val, int width) {
    double min = stats.getMin();
    double max = stats.getMax();

    int barWidth = width - 2 * insetX;

    int value = DoubleMath.roundToInt(barWidth * (val - min) / (max - min), RoundingMode.HALF_UP);

    if (!metric.moreIsBetter())
        value = barWidth - value; // maybe we have to subtract 1px here

    return value;
}

From source file:org.libreplan.business.workingday.ResourcesPerDay.java

public EffortDuration asDurationGivenWorkingDayOf(EffortDuration resourceWorkingDayDuration) {
    BigDecimal multiply = getAmount().multiply(new BigDecimal(resourceWorkingDayDuration.getSeconds()));
    if (multiply.compareTo(BigDecimal.ZERO) > 0) {
        return EffortDuration.elapsing(Math.max(1, multiply.setScale(0, RoundingMode.HALF_UP).intValue()),
                Granularity.SECONDS);/*w ww  .j  ava2  s  .  c o m*/
    } else {
        return EffortDuration.zero();
    }
}

From source file:org.specvis.logic.Functions.java

/**
 * Round given double value to N decimal places.
 * @param value/*from   ww  w  .j av  a  2  s .c om*/
 * @param places
 * @return Rounded double value.
 */
public double round(double value, int places) {
    if (places < 0)
        throw new IllegalArgumentException();
    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

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  .ja 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:me.smoe.adar.utils.cam.o.statistics.Statistics.java

private int calcScore(int cur, int total) {
    return new BigDecimal(cur).divide(new BigDecimal(total), 4, RoundingMode.HALF_UP)
            .multiply(new BigDecimal(10000)).intValue();
}

From source file:org.cirdles.ambapo.UTMToLatLong.java

/**
 * Eta-east refers to the east west direction of the UTM.
 * @param easting//from   w  w  w  .j a v a2  s .co m
 * @param meridianRadius
 * @return eta east
 */
private static BigDecimal calcEtaEast(BigDecimal easting, BigDecimal meridianRadius) {

    BigDecimal etaEast = (easting.subtract(FALSE_EASTING)).divide(SCALE_FACTOR.multiply(meridianRadius),
            PRECISION, RoundingMode.HALF_UP);

    return etaEast;
}

From source file:uk.ac.leeds.ccg.andyt.projects.fluvialglacial.SlopeAreaAnalysis.java

public void run(TreeMap<Integer, Object[]> allData, File outDir, File outFile2, int minNumberOfDataPoints) {
    File outfile;//w w  w. j  ava  2  s.c  om
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(outFile2);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(SlopeAreaAnalysis.class.getName()).log(Level.SEVERE, null, ex);
    }
    //pw.println("ID, log(Slope)");
    pw.println("ID, Slope");
    int dataWidth = 500;//400;//250;
    int dataHeight = 500;//657;
    String xAxisLabel = "x = log(Slope)";
    String yAxisLabel = "y = log(Upstream Accumulation Area)";
    boolean drawOriginLinesOnPlot;
    //        drawOriginLinesOnPlot = true;
    drawOriginLinesOnPlot = false;
    int decimalPlacePrecisionForCalculations = 10;
    int decimalPlacePrecisionForDisplay = 3;
    RoundingMode aRoundingMode = RoundingMode.HALF_UP;
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    SlopeAreaScatterPlot plot;

    String format = "PNG";
    String title;

    Iterator<Integer> ite;
    ite = allData.keySet().iterator();
    int ID;
    Object[] data;
    while (ite.hasNext()) {
        ID = ite.next();
        //if (ID == 388) {

        data = allData.get(ID);
        ArrayList<Generic_XYNumericalData> theGeneric_XYNumericalData;
        theGeneric_XYNumericalData = (ArrayList<Generic_XYNumericalData>) data[0];
        int np;
        np = theGeneric_XYNumericalData.size();
        for (int degree = 2; degree < 3; degree++) {
            title = "GlacierID " + ID + ", n = " + np;
            //title += ", degree = " + degree;
            File outDir2 = new File(outDir, "degree" + degree);
            outDir2.mkdirs();
            outfile = new File(outDir2, "SlopeUAAScatterPlot" + ID + ".PNG");
            if (np >= minNumberOfDataPoints) {
                plot = new SlopeAreaScatterPlot(degree, data, executorService, outfile, format, title,
                        dataWidth, dataHeight, xAxisLabel, yAxisLabel, drawOriginLinesOnPlot,
                        decimalPlacePrecisionForCalculations, decimalPlacePrecisionForDisplay, aRoundingMode);
                //plot.setData(plot.getDefaultData());
                //plot.setStartAgeOfEndYearInterval(0); // To avoid null pointer
                plot.run();
                if (plot.isHump) {
                    System.out.println("" + ID + ", " + plot.xAtMaxy2);
                    double x = Math.pow(10.0d, plot.xAtMaxy2);
                    //pw.println("" + ID + ", " + plot.xAtMaxy2);
                    pw.println("" + ID + ", " + x);
                }
            }
        }
        pw.flush();
        //}
    }
    pw.close();
}

From source file:de.appsolve.padelcampus.controller.ranking.RankingController.java

@RequestMapping("{participantUUID}/history")
public ModelAndView getRankingHistory(@PathVariable() String participantUUID) throws JsonProcessingException {
    Participant participant = participantDAO.findByUUID(participantUUID);
    if (participant == null) {
        throw new ResourceNotFoundException();
    }//ww w . j  a  v a  2s . co m

    LocalDate endDate = LocalDate.now();
    LocalDate startDate = endDate.minusDays(365);
    Map<Gender, Map<Long, BigDecimal>> genderDateRankingMap = new TreeMap<>();
    for (Gender gender : EnumSet.of(Gender.male, Gender.female, Gender.unisex)) {
        List<Ranking> rankings = rankingUtil.getPlayerRanking(gender, participant, startDate, endDate);
        if (rankings != null && !rankings.isEmpty()) {
            Map<Long, BigDecimal> dateRankingMap = new TreeMap<>();
            for (Ranking ranking : rankings) {
                LocalDate date = ranking.getDate();
                Long millis = date.toDateTimeAtStartOfDay().getMillis();
                dateRankingMap.put(millis, ranking.getValue().setScale(0, RoundingMode.HALF_UP));
            }
            genderDateRankingMap.put(gender, dateRankingMap);
        }
    }
    ModelAndView mav = new ModelAndView(getPath() + "ranking/history");
    mav.addObject("Participant", participant);
    mav.addObject("GenderDateRankingMap", genderDateRankingMap);
    mav.addObject("ChartMap", objectMapper.writeValueAsString(genderDateRankingMap));
    return mav;
}