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:NumberFormatRounding.java

public static void main(String[] args) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);/*from w w w .  j  a va  2  s  .c  o m*/
    nf.setRoundingMode(RoundingMode.HALF_DOWN);
    System.out.println("Default rounding mode: " + nf.getRoundingMode());
    System.out.println("123.454 rounds to " + nf.format(123.454));
    System.out.println("123.455 rounds to " + nf.format(123.455));
    System.out.println("123.456 rounds to " + nf.format(123.456));
    System.out.println();

}

From source file:NumberFormatRounding.java

public static void main(String[] args) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);//from   ww  w. j a va  2s.  c  o  m
    nf.setRoundingMode(RoundingMode.HALF_DOWN);
    System.out.println("Default rounding mode: " + nf.getRoundingMode());
    System.out.println("123.454 rounds to " + nf.format(123.454));
    System.out.println("123.455 rounds to " + nf.format(123.455));
    System.out.println("123.456 rounds to " + nf.format(123.456));
    System.out.println();

    nf.setRoundingMode(RoundingMode.FLOOR);
    System.out.println("Default rounding mode: " + nf.getRoundingMode());
    System.out.println("123.454 rounds to " + nf.format(123.454));
    System.out.println("123.455 rounds to " + nf.format(123.455));
    System.out.println("123.456 rounds to " + nf.format(123.456));
    System.out.println();

    nf.setMaximumFractionDigits(2);
    nf.setRoundingMode(RoundingMode.CEILING);
    System.out.println("Default rounding mode: " + nf.getRoundingMode());
    System.out.println("123.454 rounds to " + nf.format(123.454));
    System.out.println("123.455 rounds to " + nf.format(123.455));
    System.out.println("123.456 rounds to " + nf.format(123.456));
    System.out.println();

}

From source file:fr.cph.stock.android.entity.EntityBuilder.java

private void buildUser() throws JSONException {
    user = new User();
    JSONObject jsonUser = json.getJSONObject("user");

    String userIdStr = jsonUser.getString("id");
    user.setUserId(userIdStr);/*from   w ww  .j  av a  2s  .  c  o  m*/

    String localeStr = jsonUser.getString("locale");
    String language = localeStr.split("_")[0];
    String country = localeStr.split("_")[1];
    Locale locale = new Locale(language, country);
    user.setLocale(locale);

    formatCurrencyZero = NumberFormat.getCurrencyInstance(user.getLocale());
    formatCurrencyZero.setMaximumFractionDigits(0);
    formatCurrencyZero.setMinimumFractionDigits(0);
    formatCurrencyZero.setRoundingMode(RoundingMode.HALF_DOWN);

    formatCurrencyOne = NumberFormat.getCurrencyInstance(user.getLocale());
    formatCurrencyOne.setMaximumFractionDigits(1);
    formatCurrencyOne.setMinimumFractionDigits(0);
    formatCurrencyOne.setRoundingMode(RoundingMode.HALF_DOWN);

    formatCurrencyTwo = NumberFormat.getCurrencyInstance(user.getLocale());
    formatCurrencyTwo.setMaximumFractionDigits(2);
    formatCurrencyTwo.setMinimumFractionDigits(0);
    formatCurrencyTwo.setRoundingMode(RoundingMode.HALF_DOWN);

    formatLocaleZero = NumberFormat.getInstance(user.getLocale());
    formatLocaleZero.setMaximumFractionDigits(0);
    formatLocaleZero.setMinimumFractionDigits(0);
    formatLocaleZero.setRoundingMode(RoundingMode.HALF_DOWN);

    formatLocaleOne = NumberFormat.getInstance(user.getLocale());
    formatLocaleOne.setMaximumFractionDigits(1);
    formatLocaleOne.setMinimumFractionDigits(0);
    formatLocaleOne.setRoundingMode(RoundingMode.HALF_DOWN);

    formatLocaleTwo = NumberFormat.getInstance(user.getLocale());
    formatLocaleTwo.setMaximumFractionDigits(2);
    formatLocaleTwo.setMinimumFractionDigits(0);
    formatLocaleTwo.setRoundingMode(RoundingMode.HALF_DOWN);

    String datePattern = jsonUser.getString("datePattern");
    user.setDatePattern(datePattern);

    String datePatternWithoutHourMin = jsonUser.getString("datePatternWithoutHourMin");
    user.setDatePatternWithoutHourMin(datePatternWithoutHourMin);

    JSONObject lastUpdateJSON = jsonUser.getJSONObject("lastUpdate");
    user.setLastUpdate(extractDate(lastUpdateJSON, user.getDatePattern()));
}

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static RoundingMode getRoundingMode() {
    String roundingMode = ApplicationProperties.getRoundingMode();
    if ("HALF_UP".equals(roundingMode) || roundingMode == null) {
        return RoundingMode.HALF_UP;
    }//  w  ww. j a v  a2s  .  com
    if ("HALF_DOWN".equals(roundingMode)) {
        return RoundingMode.HALF_DOWN;
    }
    throw new IllegalArgumentException(String.format("Unsupported rounding mode: %s", roundingMode));
}

From source file:com.github.rinde.gpem17.eval.SimRuntimeLogger.java

void write() {
    lastWrite = System.currentTimeMillis();
    StringBuilder sb = new StringBuilder();
    String timestamp = ISODateTimeFormat.dateHourMinuteSecond().print(lastWrite);

    long sum = 0;
    double[] arr = new double[receivedResults.size()];
    for (int i = 0; i < receivedResults.size(); i++) {
        SimResult info = (SimResult) receivedResults.get(i).getResultObject();
        sum += info.getStats().computationTime;
        arr[i] = info.getStats().computationTime;
    }/*from  ww  w.  j  a va 2s . co  m*/
    double mean = sum / receivedResults.size();
    long sd = DoubleMath.roundToLong(new StandardDeviation().evaluate(arr, mean), RoundingMode.HALF_DOWN);
    long longMean = DoubleMath.roundToLong(mean, RoundingMode.HALF_DOWN);

    sb.append(timestamp).append(",").append(receivedSims).append("/").append(totalSims).append(", Received ")
            .append(receivedResults.size()).append(" results in last minute, avg comp time,")
            .append(PeriodFormat.getDefault().print(new Period(longMean))).append(", standard deviation,")
            .append(PeriodFormat.getDefault().print(new Period(sd))).append(System.lineSeparator());
    try {
        Files.append(sb.toString(), progressFile, Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    receivedResults.clear();
}

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

/**
 * ?12:05??// ww  w  .j a  v  a  2 s  .com
 * 
 * @return
 */
public String initJobReport() {
    jobResult = JobResult.succcessResult();
    try {
        Date startTime = DateTimeUtil.getDateBeforeOrAfterV2(-1);
        Date endTime = DateTimeUtil.getDateBeforeOrAfterV2(0);

        int jobNum = jobBO.getCurrentJobNum();
        int successNum = reportJobRtBO.getCount(ReportJobRtDO.REPORT_JOB_RT_STATUS_SUCCESS, startTime, endTime);
        int errorNum = reportJobRtBO.getCount(ReportJobRtDO.REPORT_JOB_RT_STATUS_TIME_OUT, startTime, endTime)
                + reportJobRtBO.getCount(ReportJobRtDO.REPORT_JOB_RT_STATUS_FAILED, startTime, endTime);
        /*
         * 
         * reportJobRtBO.getCount(ReportJobRtDO.REPORT_JOB_RT_STATUS_DELETE,
         * startTime, endTime) ??
         */

        if (successNum == 0 && errorNum == 0) {
            return SUCCESS;
        }

        double rt = reportJobRtBO.getAverageRt(startTime, endTime);

        ReportJobDO job = new ReportJobDO();
        job.setJobNum(Long.valueOf(jobNum));
        job.setErrorNum(Long.valueOf(errorNum));
        job.setSuccessNum(Long.valueOf(successNum));
        job.setRt(new BigDecimal(rt).setScale(2, RoundingMode.HALF_DOWN));
        job.setReportTime(DateTimeUtil.getDateBeforeOrAfterV2(-1));
        reportJobBO.saveOrUpdateReportJob(job);
    } catch (Exception e) {
        jobResult = JobResult.errorResult(JobResult.RESULTCODE_OTHER_ERR, e.getMessage());
        logger.error("initJobReport error", e);

    }
    return SUCCESS;
}

From source file:com.ibk.ltw.domain.Product.java

public String getVatAsText() {
    BigDecimal vatInPercent = new BigDecimal(getVatInPerThousand()).movePointLeft(3);
    NumberFormat percentFormat = NumberFormat.getPercentInstance(Locale.US);
    percentFormat.setMaximumFractionDigits(1);
    percentFormat.setRoundingMode(RoundingMode.HALF_DOWN);
    return percentFormat.format(vatInPercent);
}

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

/**
 * Generates a value tag based on the type of the value.
 *//*from  w w w .j  ava  2s. c o  m*/
private void generateValue(Object value) {
    if (value == null) {
        tag("string", "void");
    } else {
        Class<?> clazz = value.getClass();
        if (clazz == String.class || clazz == Character.class) {
            sb.append(StringEscapeUtils.escapeXml(value.toString()));
        } else if (clazz == Long.class || clazz == Integer.class || clazz == Short.class
                || clazz == Byte.class) {
            tag("int", value.toString());
        } else if (clazz == Double.class) {
            tag("double", String.valueOf(((Double) value).doubleValue()));
        } else if (clazz == Float.class) {
            BigDecimal bd = new BigDecimal((Float) value);
            generateValue(bd.setScale(6, RoundingMode.HALF_DOWN).doubleValue());
        } else if (clazz == BigDecimal.class) {
            generateValue(((BigDecimal) value).setScale(6, RoundingMode.HALF_DOWN).doubleValue());
        } else if (clazz == Boolean.class) {
            tag("boolean", ((Boolean) value).booleanValue() ? "1" : "0");
        } else if (clazz == Date.class) {
            tag("dateTime.iso8601", xmlRpcDateFormat.format(((Date) value)));
        } else if (value instanceof Calendar) {
            generateValue(((Calendar) value).getTime());
        } else if (value instanceof byte[]) {
            tag("base64", Base64.getEncoder().encodeToString((byte[]) value));
        } else if (clazz.isArray() || value instanceof List) {
            sb.append("<array><data>");

            Object[] array = null;
            if (value instanceof List) {
                array = ((List<?>) value).toArray();
            } else {
                array = (Object[]) value;
            }
            for (Object arrayObject : array) {
                sb.append("<value>");
                generateValue(arrayObject);
                sb.append("</value>");
            }

            sb.append("</data></array>");
        } else if (value instanceof Map) {
            sb.append("<struct>");

            for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
                sb.append("<member>");
                sb.append("<name>").append(entry.getKey()).append("</name>");
                sb.append("<value>");
                generateValue(entry.getValue());
                sb.append("</value>");
                sb.append("</member>");
            }

            sb.append("</struct>");
        } else {
            throw new RuntimeException("Unsupported XML-RPC Type: " + value.getClass());
        }
    }
}

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

@Override
protected MoveProgress doFollowPath(MovingRoadUser object, Queue<Point> path, TimeLapse time) {
    final long startTimeConsumed = time.getTimeConsumed();
    Point loc = objLocs.get(object);

    double traveled = 0;
    final double speed = min(unitConversion.toInSpeed(object.getSpeed()), maxSpeed);
    if (speed == 0d) {
        // FIXME add test for this case, also check GraphRoadModel
        final Measure<Double, Length> dist = Measure.valueOf(0d, getDistanceUnit());
        final Measure<Long, Duration> dur = Measure.valueOf(0L, time.getTimeUnit());
        return MoveProgress.create(dist, dur, new ArrayList<Point>());
    }//from   ww w  . jav a  2  s.co m

    final List<Point> travelledNodes = new ArrayList<>();
    while (time.hasTimeLeft() && !path.isEmpty()) {
        checkArgument(isPointInBoundary(path.peek()),
                "points in the path must be within the predefined boundary of the " + "plane");

        // distance in internal time unit that can be traveled with timeleft
        final double travelDistance = speed * unitConversion.toInTime(time.getTimeLeft(), time.getTimeUnit());
        final double stepLength = unitConversion.toInDist(Point.distance(loc, path.peek()));

        if (travelDistance >= stepLength) {
            loc = path.remove();
            travelledNodes.add(loc);

            final long timeSpent = DoubleMath.roundToLong(
                    unitConversion.toExTime(stepLength / speed, time.getTimeUnit()), RoundingMode.HALF_DOWN);
            time.consume(timeSpent);
            traveled += stepLength;
        } else {
            final Point diff = Point.diff(path.peek(), loc);

            if (stepLength - travelDistance < DELTA) {
                loc = path.peek();
                traveled += stepLength;
            } else {
                final double perc = travelDistance / stepLength;
                loc = new Point(loc.x + perc * diff.x, loc.y + perc * diff.y);
                traveled += travelDistance;
            }
            time.consumeAll();

        }
    }
    objLocs.put(object, loc);

    // convert to external units
    final Measure<Double, Length> distTraveled = unitConversion.toExDistMeasure(traveled);
    final Measure<Long, Duration> timeConsumed = Measure.valueOf(time.getTimeConsumed() - startTimeConsumed,
            time.getTimeUnit());
    return MoveProgress.create(distTraveled, timeConsumed, travelledNodes);
}

From source file:com.nubits.nubot.utils.Utils.java

public static double round(double value, int places) {
    if (places < 0) {
        throw new IllegalArgumentException();
    }/*from  w w  w  .ja va  2s.  c om*/

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_DOWN);
    return bd.doubleValue();
}