Example usage for java.math RoundingMode HALF_DOWN

List of usage examples for java.math RoundingMode HALF_DOWN

Introduction

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

Prototype

RoundingMode HALF_DOWN

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

Click Source Link

Document

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

Usage

From source file:com.taobao.ad.easyschedule.dao.reportjobrt.impl.JPAReportJobRtDAOImpl.java

@SuppressWarnings("unchecked")
@Override//www .j  ava 2s. c om
public List<ReportJobRtDO> findReportJobRtPageList(final ReportJobRtDO reportJobRt) {
    reportJobRt.setTotalItem(((BigInteger) this.getJpaTemplate().execute(new JpaCallback() {

        @Override
        public Object doInJpa(EntityManager em) throws PersistenceException {

            return em.createNativeQuery(
                    "select count(distinct t.JOB_NAME ,t.JOB_GROUP) from  es_report_job_rt t where t.create_time<=?1 and t.create_time>=?2")
                    .setParameter(1, reportJobRt.getQueryEndTime())
                    .setParameter(2, reportJobRt.getQueryStartTime()).getSingleResult();

        }
    })).intValue());

    List<Object[]> result = (List<Object[]>) super.getJpaTemplate().execute(new JpaCallback() {

        @Override
        public Object doInJpa(EntityManager em) throws PersistenceException {
            return em.createNativeQuery(
                    "SELECT *,a.successNum*100/a.totalNum AS successRate FROM ( SELECT  AVG(rt) AS rt,COUNT(*) AS totalNum,job_group,job_name,COUNT(CASE WHEN STATUS = 2 THEN '1' ELSE NULL END) AS successNum, COUNT(CASE WHEN STATUS > 2 THEN 'x' ELSE NULL END) AS errorNum FROM es_report_job_rt where create_time<=?1 and create_time>=?2 GROUP BY job_name,job_group  ) a ORDER BY a.job_group,successRate "
                            + (reportJobRt.isSuccessRateOrderBy() ? "desc" : ""))
                    .setParameter(1, reportJobRt.getQueryEndTime())
                    .setParameter(2, reportJobRt.getQueryStartTime()).setFirstResult(reportJobRt.getStartRow())
                    .setMaxResults(reportJobRt.getPerPageSize()).getResultList();
        }
    });

    List<ReportJobRtDO> rtList = new ArrayList<ReportJobRtDO>(result.size());

    for (Object[] o : result) {
        ReportJobRtDO rt = new ReportJobRtDO();
        if (o[0] != null) {
            rt.setShowRt(new BigDecimal(o[0].toString()).setScale(2, RoundingMode.HALF_DOWN));
        }
        rt.setTotalNum(((BigInteger) o[1]).intValue());
        rt.setJobGroup(String.valueOf(o[2]));
        rt.setJobName(String.valueOf(o[3]));
        rt.setSuccessNum(Integer.valueOf(o[4].toString()));
        rt.setErrorNum(Integer.valueOf(o[5].toString()));
        rt.setSuccessRate(new BigDecimal(o[6].toString()).setScale(2, RoundingMode.HALF_DOWN));
        rt.setErrorRate(new BigDecimal(100).subtract(rt.getSuccessRate()).setScale(2, RoundingMode.HALF_DOWN));
        rtList.add(rt);

    }
    return rtList;

}

From source file:com.taobao.ad.easyschedule.action.reportjob.ReportJobAction.java

private Double getDoubleValue(ReportJobDO job, int type) {

    switch (type) {

    case ReportJobDO.REPORT_TYPE_JOB_TOTAL_NUM:
        return job.getJobNum().doubleValue();
    case ReportJobDO.REPORT_TYPE_JOB_AGV_RT:
        return job.getRt().doubleValue();
    case ReportJobDO.REPORT_TYPE_JOB_ERROR_NUM:
        return job.getErrorNum().doubleValue();
    case ReportJobDO.REPORT_TYPE_JOB_ERROR_RATE:

        if (job.getSuccessNum() + job.getErrorNum() == 0) {
            return Double.valueOf(0);
        } else {/*from   w w  w  . j a va  2 s .c o m*/

            return new BigDecimal(100)
                    .subtract(new BigDecimal(
                            (job.getSuccessNum() * 100 + 0.0) / (job.getSuccessNum() + job.getErrorNum())))
                    .setScale(2, RoundingMode.HALF_DOWN).doubleValue();

        }
    case ReportJobDO.REPORT_TYPE_JOB_SUCCESS_NUM:
        return job.getSuccessNum().doubleValue();
    case ReportJobDO.REPORT_TYPE_JOB_SUCCESS_RATE:

        if (job.getSuccessNum() + job.getErrorNum() == 0) {
            return Double.valueOf(0);
        } else {
            return new BigDecimal((job.getSuccessNum() * 100 + 0.0) / (job.getSuccessNum() + job.getErrorNum()))
                    .setScale(2, RoundingMode.HALF_DOWN).doubleValue();

        }

    }

    return null;
}

From source file:org.eclipse.smarthome.binding.homematic.internal.communicator.message.BinRpcMessage.java

private Object readRpcValue() throws IOException {
    int type = readInt();
    switch (type) {
    case 1://from   w  w w. java  2  s  . c  o m
        return new Integer(readInt());
    case 2:
        return binRpcData[offset++] != 0 ? Boolean.TRUE : Boolean.FALSE;
    case 3:
        return readString();
    case 4:
        int mantissa = readInt();
        int exponent = readInt();
        BigDecimal bd = new BigDecimal((double) mantissa / (double) (1 << 30) * Math.pow(2, exponent));
        return bd.setScale(6, RoundingMode.HALF_DOWN).doubleValue();
    case 5:
        return new Date(readInt() * 1000);
    case 0x100:
        // Array
        int numElements = readInt();
        Collection<Object> array = new ArrayList<Object>();
        while (numElements-- > 0) {
            array.add(readRpcValue());
        }
        return array.toArray();
    case 0x101:
        // Struct
        numElements = readInt();
        Map<String, Object> struct = new TreeMap<String, Object>();
        while (numElements-- > 0) {
            String name = readString();
            struct.put(name, readRpcValue());
        }
        return struct;

    default:
        for (int i = 0; i < binRpcData.length; i++) {
            logger.info("{} {}", Integer.toHexString(binRpcData[i]), (char) binRpcData[i]);
        }
        throw new IOException("Unknown data type " + type);
    }
}

From source file:com.github.rinde.rinsim.scenario.measure.MetricsTest.java

static Times generateTimes(RandomGenerator rng, double intensity) {
    final ExponentialDistribution ed = new ExponentialDistribution(1000d / intensity);
    ed.reseedRandomGenerator(rng.nextLong());
    final List<Long> times = newArrayList();

    long sum = 0;
    while (sum < 1000) {
        sum += DoubleMath.roundToLong(ed.sample(), RoundingMode.HALF_DOWN);
        if (sum < 1000) {
            times.add(sum);//from w ww. j  a  v a 2s .  co  m
        }
    }
    return asTimes(1000, times);
}

From source file:org.openhab.binding.max.internal.message.CMessage.java

private void parseHeatingThermostatData(byte[] bytes) {
    try {//from  ww w .jav  a 2s  .  c o  m
        int plusDataStart = 18;
        int programDataStart = 11;
        tempComfort = new BigDecimal((bytes[plusDataStart] & 0xFF) / 2D);
        tempEco = new BigDecimal((bytes[plusDataStart + 1] & 0xFF) / 2D);
        tempSetpointMax = new BigDecimal((bytes[plusDataStart + 2] & 0xFF) / 2D);
        tempSetpointMin = new BigDecimal((bytes[plusDataStart + 3] & 0xFF) / 2D);
        properties.put(PROPERTY_THERMO_COMFORT_TEMP, tempComfort.setScale(1, RoundingMode.HALF_DOWN));
        properties.put(PROPERTY_THERMO_ECO_TEMP, tempEco.setScale(1, RoundingMode.HALF_DOWN));
        properties.put(PROPERTY_THERMO_MAX_TEMP_SETPOINT, tempSetpointMax.setScale(1, RoundingMode.HALF_DOWN));
        properties.put(PROPERTY_THERMO_MIN_TEMP_SETPOINT, tempSetpointMin.setScale(1, RoundingMode.HALF_DOWN));
        if (bytes.length < 211) {
            // Device is a WallMountedThermostat
            programDataStart = 4;
            logger.trace("WallThermostat byte {}: {}", bytes.length - 3,
                    Float.toString(bytes[bytes.length - 3] & 0xFF));
            logger.trace("WallThermostat byte {}: {}", bytes.length - 2,
                    Float.toString(bytes[bytes.length - 2] & 0xFF));
            logger.trace("WallThermostat byte {}: {}", bytes.length - 1,
                    Float.toString(bytes[bytes.length - 1] & 0xFF));
        } else {
            // Device is a HeatingThermostat(+)
            tempOffset = new BigDecimal((bytes[plusDataStart + 4] & 0xFF) / 2D - 3.5);
            tempOpenWindow = new BigDecimal((bytes[plusDataStart + 5] & 0xFF) / 2D);
            durationOpenWindow = new BigDecimal((bytes[plusDataStart + 6] & 0xFF) * 5);
            boostDuration = new BigDecimal(bytes[plusDataStart + 7] & 0xFF >> 5);
            boostValve = new BigDecimal((bytes[plusDataStart + 7] & 0x1F) * 5);
            decalcification = new BigDecimal(bytes[plusDataStart + 8]);
            valveMaximum = new BigDecimal((bytes[plusDataStart + 9] & 0xFF) * 100 / 255);
            valveOffset = new BigDecimal((bytes[plusDataStart + 10] & 0xFF) * 100 / 255);
            properties.put(PROPERTY_THERMO_OFFSET_TEMP, tempOffset.setScale(1, RoundingMode.HALF_DOWN));
            properties.put(PROPERTY_THERMO_WINDOW_OPEN_TEMP,
                    tempOpenWindow.setScale(1, RoundingMode.HALF_DOWN));
            properties.put(PROPERTY_THERMO_WINDOW_OPEN_DURATION,
                    durationOpenWindow.setScale(0, RoundingMode.HALF_DOWN));
            properties.put(PROPERTY_THERMO_BOOST_DURATION, boostDuration.setScale(0, RoundingMode.HALF_DOWN));
            properties.put(PROPERTY_THERMO_BOOST_VALVEPOS, boostValve.setScale(0, RoundingMode.HALF_DOWN));
            properties.put(PROPERTY_THERMO_DECALCIFICATION,
                    decalcification.setScale(0, RoundingMode.HALF_DOWN));
            properties.put(PROPERTY_THERMO_VALVE_MAX, valveMaximum.setScale(0, RoundingMode.HALF_DOWN));
            properties.put(PROPERTY_THERMO_VALVE_OFFSET, valveOffset.setScale(0, RoundingMode.HALF_DOWN));
        }
        programData = "";
        int ln = 13 * 6; // first day = Sat
        String startTime = "00:00h";
        for (int charIdx = plusDataStart + programDataStart; charIdx < (plusDataStart + programDataStart
                + 26 * 7); charIdx++) {
            if (ln % 13 == 0) {
                programData += "\r\n Day " + Integer.toString((ln / 13) % 7) + ": ";
                startTime = "00:00h";
            }
            int progTime = (bytes[charIdx + 1] & 0xFF) * 5 + (bytes[charIdx] & 0x01) * 1280;
            int progMinutes = progTime % 60;
            int progHours = (progTime - progMinutes) / 60;
            String endTime = Integer.toString(progHours) + ":" + String.format("%02d", progMinutes) + "h";
            programData += startTime + "-" + endTime + " " + Double.toString(bytes[charIdx] / 4) + "C  ";
            startTime = endTime;
            charIdx++;
            ln++;
        }
    } catch (Exception e) {
        logger.debug("Exception occurred during heater data: {}", e.getMessage(), e);
    }
    return;
}

From source file:com.github.rinde.rinsim.core.model.road.GraphRoadModel.java

@Override
protected MoveProgress doFollowPath(MovingRoadUser object, Queue<Point> path, TimeLapse time) {
    final Loc objLoc = verifyLocation(objLocs.get(object));
    Loc tempLoc = objLoc;/*from w w  w  .  j ava 2  s  .c  om*/
    final MoveProgress.Builder mpBuilder = MoveProgress.builder(unitConversion, time);

    boolean cont = true;
    long timeLeft = time.getTimeLeft();
    while (timeLeft > 0 && !path.isEmpty() && cont) {
        checkMoveValidity(tempLoc, path.peek());
        // speed in internal speed unit
        final double speed = getMaxSpeed(object, tempLoc, path.peek());
        checkState(speed >= 0, "Found a bug in getMaxSpeed, return value must be >= 0, but is %s.", speed);
        // distance that can be traveled in current conn with timeleft
        final double travelableDistance = computeTravelableDistance(tempLoc, path.peek(), speed, timeLeft,
                time.getTimeUnit());
        checkState(travelableDistance >= 0d,
                "Found a bug in computeTravelableDistance, return value must be >= 0," + " but is %s.",
                travelableDistance);
        final double connLength = unitConversion.toInDist(computeDistanceOnConnection(tempLoc, path.peek()));
        checkState(connLength >= 0d,
                "Found a bug in computeDistanceOnConnection, return value must be " + ">= 0, but is %s.",
                connLength);

        double traveledDistance;
        if (travelableDistance >= connLength) {
            // jump to next node in path (this may be a node or a point on a
            // connection)
            tempLoc = verifyLocation(asLoc(path.remove()));
            traveledDistance = connLength;
            mpBuilder.addNode(tempLoc);
        } else {
            // travelableDistance < connLength
            cont = false;
            traveledDistance = travelableDistance;
            final Connection<?> conn = getConnection(tempLoc, path.peek());
            tempLoc = verifyLocation(
                    newLoc(conn, tempLoc.relativePos + unitConversion.toExDist(travelableDistance)));
        }
        mpBuilder.addDistance(traveledDistance);
        final long timeSpent = DoubleMath.roundToLong(
                unitConversion.toExTime(traveledDistance / speed, time.getTimeUnit()), RoundingMode.HALF_DOWN);
        timeLeft -= timeSpent;
    }
    time.consume(time.getTimeLeft() - timeLeft);
    // update location and construct a MoveProgress object
    objLocs.put(object, tempLoc);
    return mpBuilder.build();
}

From source file:com.gollahalli.web.WebViewer.java

/**
 * To use this, do the following//from   ww  w.  j  ava  2  s  .c  o  m
 * <pre>
 *  {@code
 *     WebViewer webViewer = new WebViewer(loanAmountText, interestText, yearsTextMonth + monthsText, loanAmountString, yearsTextString, monthsTextString, String.valueOf(monthlyOutput), String.valueOf(bd.doubleValue()), String.valueOf(bd.doubleValue() + loanAmountText));
 *     String test = webViewer.webReturnMonthly();
 * }
 * </pre>
 *
 */
public void webReturnYearly() {
    logger.info("yearly called");
    Calculate calculate = new Calculate();

    double[][] monthlyChartYearly = calculate.fixedRateMortgageMonthlyChart(loanAmountText, interestText,
            yearsTextMonth);
    logger.info("monthly chart yearly called");
    String[] property = propertyReader();

    double[][] newYearly = new double[5][(int) yearsTextMonth];
    newYearly[0][0] = monthlyChartYearly[2][0];
    newYearly[1][0] = monthlyChartYearly[1][0];
    newYearly[2][0] = monthlyChartYearly[3][0];
    for (int i = 1; i < yearsTextMonth; i++) {
        monthlyChartYearly = calculate.fixedRateMortgageMonthlyChart(monthlyChartYearly[3][0], interestText,
                yearsTextMonth - i);
        newYearly[0][i] = monthlyChartYearly[2][0];
        newYearly[1][i] = monthlyChartYearly[1][0];
        newYearly[2][i] = monthlyChartYearly[3][0];
    }

    String html = "";
    int someNumber = 1;

    double yearlyPrincipal = 0.0;
    double yearlyInterest = 0.0;
    double yearlyBalance = loanAmountText;
    for (int i = 0; i < newYearly[0].length; i++) {
        if (i % 12 == 0 && i != 0) {
            html += "<tr><td>" + String.valueOf(someNumber++) + "</td>" + "<td class=\"text-center\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyPrincipal).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td>" + "<td class=\"text-center\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyInterest).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td>" + "<td class=\"text-right\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyBalance).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td></tr>";
            yearlyPrincipal = 0;
            yearlyInterest = 0;
        }
        yearlyPrincipal += newYearly[0][i];
        yearlyInterest += newYearly[1][i];
        yearlyBalance -= newYearly[0][i];
        if (i == newYearly[0].length - 1 && i != 0) {
            html += "<tr><td>" + String.valueOf(someNumber++) + "</td>" + "<td class=\"text-center\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyPrincipal).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td>" + "<td class=\"text-center\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyInterest).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td>" + "<td class=\"text-right\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyBalance).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td></tr>";

        }

    }

    general.templateMaker(WordUtils.capitalize(property[0]), WordUtils.capitalize(this.custName),
            WordUtils.capitalize(this.custAddress), general.getDate(), currencyMaker(loanAmount), years, months,
            " type of payment", currencyMaker(monthlyPayments), currencyMaker(totalInterest),
            currencyMaker(totalPayments), "type of time", html, property[5], WordUtils.capitalize(property[1]),
            WordUtils.capitalize(property[2]), property[3], property[4]);

}

From source file:org.goko.tinyg.controller.TinyGState.java

/**
 * @param position the position to set/*www .  j a va2 s.  co m*/
 * @throws GkException
 */
public void setWorkPosition(Tuple6b position) throws GkException {
    this.position = new Tuple6b(position);
    String x = GokoPreference.getInstance()
            .format(NumberQuantity.of(new BigDecimal(position.getX().doubleValue()), currentUnit), true);
    String y = GokoPreference.getInstance()
            .format(NumberQuantity.of(new BigDecimal(position.getY().doubleValue()), currentUnit), true);
    String z = GokoPreference.getInstance()
            .format(NumberQuantity.of(new BigDecimal(position.getZ().doubleValue()), currentUnit), true);
    updateValue(TinyG.POSITION_X, x);
    updateValue(TinyG.POSITION_Y, y);
    updateValue(TinyG.POSITION_Z, z);
    updateValue(TinyG.POSITION_A,
            new BigDecimal(position.getA().doubleValue()).setScale(3, RoundingMode.HALF_DOWN));
}

From source file:org.openhab.binding.homematic.internal.communicator.message.BinRpcMessage.java

private void addObject(Object object) {
    if (object.getClass() == String.class) {
        addInt(3);/*from  w  w  w  .  j  av a 2  s . c  om*/
        String string = (String) object;
        addInt(string.length());
        addString(string);
    } else if (object.getClass() == Boolean.class) {
        addInt(2);
        addByte(((Boolean) object).booleanValue() ? (byte) 1 : (byte) 0);
    } else if (object.getClass() == Integer.class) {
        addInt(1);
        addInt(((Integer) object).intValue());
    } else if (object.getClass() == Double.class) {
        addInt(4);
        addDouble(((Double) object).doubleValue());
    } else if (object.getClass() == Float.class) {
        addInt(4);
        BigDecimal bd = new BigDecimal((Float) object);
        addDouble(bd.setScale(6, RoundingMode.HALF_DOWN).doubleValue());
    } else if (object.getClass() == BigDecimal.class) {
        addInt(4);
        addDouble(((BigDecimal) object).setScale(6, RoundingMode.HALF_DOWN).doubleValue());
    } else if (object.getClass() == BigInteger.class) {
        addInt(4);
        addDouble(((BigInteger) object).doubleValue());
    } else if (object.getClass() == Date.class) {
        addInt(5);
        addInt((int) ((Date) object).getTime() / 1000);
    } else if (object instanceof List<?>) {
        Collection<?> list = (Collection<?>) object;
        addInt(0x100);
        addInt(list.size());
        addList(list);
    } else if (object instanceof Map<?, ?>) {
        Map<?, ?> map = (Map<?, ?>) object;
        addInt(0x101);
        addInt(map.size());
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            String key = (String) entry.getKey();
            addInt(key.length());
            addString(key);
            addList(Collections.singleton(entry.getValue()));
        }
    }
}

From source file:org.eclipse.smarthome.binding.homematic.internal.communicator.message.BinRpcMessage.java

private void addObject(Object object) {
    if (object.getClass() == String.class) {
        addInt(3);//from  w  w w .j  av  a  2 s .  c om
        String string = (String) object;
        addInt(string.length());
        addString(string);
    } else if (object.getClass() == Boolean.class) {
        addInt(2);
        addByte(((Boolean) object).booleanValue() ? (byte) 1 : (byte) 0);
    } else if (object.getClass() == Integer.class) {
        addInt(1);
        addInt(((Integer) object).intValue());
    } else if (object.getClass() == Double.class) {
        addInt(4);
        addDouble(((Double) object).doubleValue());
    } else if (object.getClass() == Float.class) {
        addInt(4);
        BigDecimal bd = new BigDecimal((Float) object);
        addDouble(bd.setScale(6, RoundingMode.HALF_DOWN).doubleValue());
    } else if (object.getClass() == BigDecimal.class) {
        addInt(4);
        addDouble(((BigDecimal) object).setScale(6, RoundingMode.HALF_DOWN).doubleValue());
    } else if (object.getClass() == BigInteger.class) {
        addInt(4);
        addDouble(((BigInteger) object).doubleValue());
    } else if (object.getClass() == Date.class) {
        addInt(5);
        addInt((int) ((Date) object).getTime() / 1000);
    } else if (object instanceof List<?>) {
        Collection<?> list = (Collection<?>) object;
        addInt(0x100);
        addInt(list.size());
        addList(list);
    } else if (object instanceof Map<?, ?>) {
        Map<?, ?> map = (Map<?, ?>) object;
        addInt(0x101);
        addInt(map.size());
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            String key = (String) entry.getKey();
            if (key != null) {
                addInt(key.length());
                addString(key);
                addList(Collections.singleton(entry.getValue()));
            }
        }
    }
}