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.libreplan.business.orders.entities.OrderLine.java

public void setBudget(BigDecimal budget) {
    Validate.isTrue(budget.compareTo(BigDecimal.ZERO) >= 0, "budget cannot be negative");
    this.budget = budget.setScale(2, RoundingMode.HALF_UP);
}

From source file:net.mikaboshi.intra_mart.tools.log_stats.formatter.TemplateFileReportFormatter.java

/**
 * ??URL??N?/*from   w  ww.ja v  a2s .  c  om*/
 * @param report
 * @param rootMap
 */
private void setRequestUrlRank(Report report, Map<String, Object> rootMap) {

    Map<String, Object> requestUrlRank = new HashMap<String, Object>();
    rootMap.put("requestUrlRank", requestUrlRank);

    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    requestUrlRank.put("list", list);

    List<RequestUrlReportEntry> reportList = report.getRequestUrlReportList();

    requestUrlRank.put("size", report.getParameter().getRequestUrlRankSize());
    requestUrlRank.put("total", reportList.size());

    MathContext percentMathContext = new MathContext(2, RoundingMode.HALF_UP);

    int i = 0;

    for (RequestUrlReportEntry entry : reportList) {

        if (++i > report.getParameter().getRequestUrlRankSize()) {
            break;
        }

        Map<String, Object> row = new HashMap<String, Object>();
        list.add(row);

        row.put("url", entry.url);
        row.put("count", entry.count);
        row.put("pageTimeSum", entry.pageTimeSum);
        row.put("pageTimeAverage", entry.pageTimeAverage);
        row.put("pageTimeMin", entry.pageTimeMin);
        row.put("pageTimeMedian", entry.pageTimeMedian);
        row.put("pageTime90Percent", entry.pageTime90Percent);
        row.put("pageTimeMax", entry.pageTimeMax);
        row.put("pageTimeStandardDeviation", entry.pageTimeStandardDeviation);
        row.put("countRate", new BigDecimal(entry.countRate * 100, percentMathContext).doubleValue());
        row.put("pageTimeRate", new BigDecimal(entry.pageTimeRate * 100, percentMathContext).doubleValue());

        if (reportParameter.isJsspPath()) {
            row.put("jsspPath", getJsspPath(entry.url));
        }
    }
}

From source file:org.eclipse.smarthome.binding.wemo.handler.WemoHandler.java

@Override
public void onValueReceived(String variable, String value, String service) {

    logger.debug("Received pair '{}':'{}' (service '{}') for thing '{}'",
            new Object[] { variable, value, service, this.getThing().getUID() });

    updateStatus(ThingStatus.ONLINE);/*w ww. j a v a2  s  . co  m*/

    this.stateMap.put(variable, value);

    if (getThing().getThingTypeUID().getId().equals("insight")) {
        String insightParams = stateMap.get("InsightParams");

        if (insightParams != null) {

            String[] splitInsightParams = insightParams.split("\\|");

            if (splitInsightParams[0] != null) {
                OnOffType binaryState = null;
                binaryState = splitInsightParams[0].equals("0") ? OnOffType.OFF : OnOffType.ON;
                if (binaryState != null) {
                    logger.trace("New InsightParam binaryState '{}' for device '{}' received", binaryState,
                            getThing().getUID());
                    updateState(CHANNEL_STATE, binaryState);
                }
            }

            long lastChangedAt = 0;
            try {
                lastChangedAt = Long.parseLong(splitInsightParams[1]) * 1000; // convert s to ms
            } catch (NumberFormatException e) {
                logger.error("Unable to parse lastChangedAt value '{}' for device '{}'; expected long",
                        splitInsightParams[1], getThing().getUID());
            }
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTimeInMillis(lastChangedAt);
            State lastChangedAtState = new DateTimeType(cal);
            if (lastChangedAt != 0) {
                logger.trace("New InsightParam lastChangedAt '{}' for device '{}' received", lastChangedAtState,
                        getThing().getUID());
                updateState(CHANNEL_LASTCHANGEDAT, lastChangedAtState);
            }

            State lastOnFor = DecimalType.valueOf(splitInsightParams[2]);
            if (lastOnFor != null) {
                logger.trace("New InsightParam lastOnFor '{}' for device '{}' received", lastOnFor,
                        getThing().getUID());
                updateState(CHANNEL_LASTONFOR, lastOnFor);
            }

            State onToday = DecimalType.valueOf(splitInsightParams[3]);
            if (onToday != null) {
                logger.trace("New InsightParam onToday '{}' for device '{}' received", onToday,
                        getThing().getUID());
                updateState(CHANNEL_ONTODAY, onToday);
            }

            State onTotal = DecimalType.valueOf(splitInsightParams[4]);
            if (onTotal != null) {
                logger.trace("New InsightParam onTotal '{}' for device '{}' received", onTotal,
                        getThing().getUID());
                updateState(CHANNEL_ONTOTAL, onTotal);
            }

            State timespan = DecimalType.valueOf(splitInsightParams[5]);
            if (timespan != null) {
                logger.trace("New InsightParam timespan '{}' for device '{}' received", timespan,
                        getThing().getUID());
                updateState(CHANNEL_TIMESPAN, timespan);
            }

            State averagePower = DecimalType.valueOf(splitInsightParams[6]); // natively given in W
            if (averagePower != null) {
                logger.trace("New InsightParam averagePower '{}' for device '{}' received", averagePower,
                        getThing().getUID());
                updateState(CHANNEL_AVERAGEPOWER, averagePower);
            }

            BigDecimal currentMW = new BigDecimal(splitInsightParams[7]);
            State currentPower = new DecimalType(currentMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate
            // mW to W
            if (currentPower != null) {
                logger.trace("New InsightParam currentPower '{}' for device '{}' received", currentPower,
                        getThing().getUID());
                updateState(CHANNEL_CURRENTPOWER, currentPower);
            }

            BigDecimal energyTodayMWMin = new BigDecimal(splitInsightParams[8]);
            // recalculate mW-mins to Wh
            State energyToday = new DecimalType(
                    energyTodayMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP));
            if (energyToday != null) {
                logger.trace("New InsightParam energyToday '{}' for device '{}' received", energyToday,
                        getThing().getUID());
                updateState(CHANNEL_ENERGYTODAY, energyToday);
            }

            BigDecimal energyTotalMWMin = new BigDecimal(splitInsightParams[9]);
            // recalculate mW-mins to Wh
            State energyTotal = new DecimalType(
                    energyTotalMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP));
            if (energyTotal != null) {
                logger.trace("New InsightParam energyTotal '{}' for device '{}' received", energyTotal,
                        getThing().getUID());
                updateState(CHANNEL_ENERGYTOTAL, energyTotal);
            }

            BigDecimal standByLimitMW = new BigDecimal(splitInsightParams[10]);
            State standByLimit = new DecimalType(
                    standByLimitMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate
            // mW to W
            if (standByLimit != null) {
                logger.trace("New InsightParam standByLimit '{}' for device '{}' received", standByLimit,
                        getThing().getUID());
                updateState(CHANNEL_STANDBYLIMIT, standByLimit);
            }
        }

    } else {
        State state = stateMap.get("BinaryState").equals("0") ? OnOffType.OFF : OnOffType.ON;

        logger.debug("State '{}' for device '{}' received", state, getThing().getUID());

        if (state != null) {
            if (getThing().getThingTypeUID().getId().equals("motion")) {
                updateState(CHANNEL_MOTIONDETECTION, state);
                if (state.equals(OnOffType.ON)) {
                    State lastMotionDetected = new DateTimeType();
                    updateState(CHANNEL_LASTMOTIONDETECTED, lastMotionDetected);
                }
            } else {
                updateState(CHANNEL_STATE, state);
            }
        }
    }
}

From source file:org.efaps.esjp.accounting.transaction.Calculation_Base.java

/**
 * Gets the JS for fill up.//from  w  ww . j  a  va2  s .c  o  m
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _parameterClone the parameter clone
 * @return the JS 4 fill up
 * @throws EFapsException on error
 */
protected StringBuilder getJS4FillUp(final Parameter _parameter, final Parameter _parameterClone)
        throws EFapsException {
    final StringBuilder ret = new StringBuilder();
    try {
        String postfix = null;
        boolean eval = true;
        while (eval) {
            eval = postfix == null;
            postfix = postfix == null ? "Debit" : "Credit";
            final String[] selected = _parameter.getParameterValues("posSelect_" + postfix);
            if (ArrayUtils.isNotEmpty(selected)) {
                for (int i = 0; i < selected.length; i++) {
                    if (BooleanUtils.toBoolean(selected[i])) {
                        eval = false;
                        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();

                        final Instance periodInst = new Period().evaluateCurrentPeriod(_parameterClone);
                        final Instance periodCurrenycInstance = new Period().getCurrency(periodInst)
                                .getInstance();

                        final BigDecimal sumDebit = getSum4UI(_parameter, "Debit", null, null);
                        final BigDecimal sumCredit = getSum4UI(_parameter, "Credit", null, null);
                        final BigDecimal diff = "Debit".equals(postfix) ? sumCredit.subtract(sumDebit)
                                : sumDebit.subtract(sumCredit);

                        final String currAmountStr = _parameter.getParameterValues("amount_" + postfix)[i];
                        final BigDecimal currAmount = StringUtils.isEmpty(currAmountStr) ? BigDecimal.ZERO
                                : (BigDecimal) formater.parse(currAmountStr);

                        final RateInfo rateInfo = getRateInfo4UI(_parameterClone, "_" + postfix, i);

                        final BigDecimal currAmountRate = Currency.convertToCurrency(_parameter, currAmount,
                                rateInfo, null, periodCurrenycInstance).setScale(2, RoundingMode.HALF_UP);

                        final BigDecimal targetRate = currAmountRate.add(diff);

                        if (BigDecimal.ZERO.compareTo(targetRate) < 0) {
                            final RateInfo revRateInfo = rateInfo.reverse();
                            final BigDecimal target = Currency.convertToCurrency(_parameter, targetRate,
                                    revRateInfo, null, rateInfo.getCurrencyInstance())
                                    .setScale(2, RoundingMode.HALF_UP);

                            final String amountStr = formater.format(target);
                            final String amountRateStr = formater.format(targetRate);

                            ret.append(getSetFieldValue(i, "amount_" + postfix, amountStr))
                                    .append(getSetFieldValue(i, "amountRate_" + postfix, amountRateStr));
                            ParameterUtil.setParameterValue(_parameterClone, "amount_" + postfix, i, amountStr);
                            ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + postfix, i,
                                    amountRateStr);

                            final BigDecimal sumDebit2 = getSum4UI(_parameterClone, "Debit", null, null);
                            final BigDecimal sumCredit2 = getSum4UI(_parameterClone, "Credit", null, null);

                            final String sumDebitStr = formater.format(sumDebit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumCreditStr = formater.format(sumCredit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumTotalStr = formater.format(sumDebit2.subtract(sumCredit2).abs())
                                    + " " + new Period().getCurrency(periodInst).getSymbol();

                            ret.append(getSetFieldValue(0, "sumDebit", sumDebitStr))
                                    .append(getSetFieldValue(0, "sumCredit", sumCreditStr))
                                    .append(getSetFieldValue(0, "sumTotal", sumTotalStr));
                            break;
                        }
                    }
                }
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:at.alladin.rmbt.qos.testscript.TestScriptInterpreter.java

/**
 * /*w  w w .j  ava  2  s .c  om*/
 * @param args
 * @return
 * @throws ScriptException
 */
private static Object parse(String[] args, Hstore hstore, Object object, ResultOptions options)
        throws ScriptException {

    if (object == null) {
        throw new ScriptException(ScriptException.ERROR_RESULT_IS_NULL + " PARSE");
    }

    HstoreParser<?> parser = hstore.getParser(object.getClass());

    if (args.length < 1) {
        throw new ScriptException(ScriptException.ERROR_INVALID_ARGUMENT_COUNT + " PARSE: " + args.length);
    }
    if (parser == null) {
        throw new ScriptException(ScriptException.ERROR_PARSER_IS_NULL + " PARSE");
    }

    try {
        Pattern p = PATTERN_ARRAY;
        Matcher m = p.matcher(args[0]);

        if (m.find()) {
            String param = m.group(1);
            int index = Integer.valueOf(m.group(2));
            Object array = parser.getValue(param, object);

            Object indexedObject = null;
            if (array != null) {
                if (List.class.isAssignableFrom(array.getClass())) {
                    indexedObject = ((List<?>) array).get(index);
                } else if (Collection.class.isAssignableFrom(array.getClass())) {
                    Iterator<?> iterator = ((Collection<?>) array).iterator();
                    int counter = 0;
                    while (iterator.hasNext()) {
                        Object o = iterator.next();
                        if ((counter++) == index) {
                            indexedObject = o;
                            break;
                        }
                    }
                }

                if (args.length > 1) {
                    String[] nextArgs = new String[args.length - 1];
                    nextArgs = Arrays.copyOfRange(args, 1, args.length);
                    return parse(nextArgs, hstore, indexedObject, options);
                } else {
                    return indexedObject;
                }
            }
        } else {
            Object value = parser.getValue(args[0], object);
            if (args.length > 1) {
                try {
                    long divisor = Long.parseLong(args[1]);
                    int precision = 2;
                    boolean groupingUsed = false;
                    if (args.length > 2) {
                        precision = Integer.parseInt(args[2]);
                    }
                    if (args.length > 3) {
                        groupingUsed = ("t".equals(args[3].toLowerCase())
                                || "true".equals(args[3].toLowerCase()));
                    }
                    NumberFormat format = (options != null ? DecimalFormat.getInstance(options.getLocale())
                            : DecimalFormat.getInstance());
                    format.setMaximumFractionDigits(precision);
                    format.setGroupingUsed(groupingUsed);
                    format.setRoundingMode(RoundingMode.HALF_UP);
                    //System.out.println("Converting number: " + args[0] + "=" + String.valueOf(value));
                    BigDecimal number = new BigDecimal(String.valueOf(value));
                    return format.format(number.divide(new BigDecimal(divisor)));
                } catch (Exception e) {
                    //can not return parsed element
                }
            }
            //System.out.println("PARAM object: " + args[0] + " -> " + value + " of " + object.toString());
            return value;
        }
    } catch (HstoreParseException e) {
        throw new ScriptException(ScriptException.ERROR_UNKNOWN + " PARSE: " + e.getMessage());
    } catch (Throwable t) {
        throw new ScriptException(ScriptException.ERROR_UNKNOWN + " PARSE: " + t.getMessage());
    }

    return null;
}

From source file:com.ibm.og.client.ApacheClient.java

private Gson createGson() {
    return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setLongSerializationPolicy(LongSerializationPolicy.STRING)
            .registerTypeAdapter(Double.class, new TypeAdapter<Double>() {
                @Override//from   w  w  w . j av  a 2  s.  co m
                public void write(final JsonWriter out, final Double value) throws IOException {
                    // round decimals to 2 places
                    out.value(new BigDecimal(value).setScale(2, RoundingMode.HALF_UP).doubleValue());
                }

                @Override
                public Double read(final JsonReader in) throws IOException {
                    return in.nextDouble();
                }
            }.nullSafe()).create();
}

From source file:org.fenixedu.academic.ui.struts.action.departmentAdmOffice.SummariesControlAction.java

private List<DetailSummaryElement> getExecutionCourseResume(final ExecutionSemester executionSemester,
        Collection<Professorship> professorships) {
    List<DetailSummaryElement> allListElements = new ArrayList<DetailSummaryElement>();
    LocalDate today = new LocalDate();
    LocalDate oneWeekBeforeToday = today.minusDays(8);
    for (Professorship professorship : professorships) {
        BigDecimal summariesGiven = EMPTY;
        BigDecimal notTaughtSummaries = EMPTY;
        if (professorship.belongsToExecutionPeriod(executionSemester)) {
            for (Shift shift : professorship.getExecutionCourse().getAssociatedShifts()) {

                // Get the number of summaries given
                summariesGiven = getSummariesGiven(professorship, shift, summariesGiven, oneWeekBeforeToday);
                // Get the number of not taught summaries
                notTaughtSummaries = getNotTaughtSummaries(professorship, shift, notTaughtSummaries,
                        oneWeekBeforeToday);
            }//from   ww  w. jav a2  s .  c  om
            summariesGiven = summariesGiven.setScale(1, RoundingMode.HALF_UP);
            notTaughtSummaries = notTaughtSummaries.setScale(1, RoundingMode.HALF_UP);

            Teacher teacher = professorship.getTeacher();
            String categoryName = null;
            if (teacher != null) {
                final Optional<TeacherAuthorization> authorization = teacher
                        .getTeacherAuthorization(executionSemester.getAcademicInterval());

                categoryName = authorization.isPresent()
                        ? authorization.get().getTeacherCategory().getName().getContent()
                        : null;

            }

            String siglas = getSiglas(professorship);

            String teacherEmail = professorship.getPerson().getDefaultEmailAddress() != null
                    ? professorship.getPerson().getDefaultEmailAddress().getPresentationValue()
                    : null;

            DetailSummaryElement listElementDTO = new DetailSummaryElement(professorship.getPerson().getName(),
                    professorship.getExecutionCourse().getNome(),
                    teacher != null ? teacher.getTeacherId() : null, teacherEmail, categoryName, summariesGiven,
                    notTaughtSummaries, siglas);

            allListElements.add(listElementDTO);
        }
    }
    return allListElements;
}

From source file:org.ethereum.rpc.Web3Impl.java

public String eth_hashrate() {
    BigDecimal hashesPerSecond = BigDecimal.ZERO;
    if (RskSystemProperties.RSKCONFIG.minerServerEnabled()) {
        BigInteger hashesPerHour = this.worldManager.getHashRateCalculator().calculateNodeHashRate(1L,
                TimeUnit.HOURS);//w  w w .j av a2 s. c  o  m
        hashesPerSecond = new BigDecimal(hashesPerHour).divide(new BigDecimal(TimeUnit.HOURS.toSeconds(1)), 3,
                RoundingMode.HALF_UP);
    }

    String result = hashesPerSecond.toString();

    if (logger.isDebugEnabled())
        logger.debug("eth_hashrate(): " + result);

    return result;
}

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

private static RoundingMode getRoundingModeFromString(String modeStr, String type,
        RoundingMode defaultRoundingMode) {
    if (StringUtils.isBlank(modeStr)) {
        return defaultRoundingMode;
    }//from w w  w .jav  a  2s.co m
    RoundingMode mode = null;
    if (modeStr.equals("FLOOR")) {
        mode = RoundingMode.FLOOR;
    } else if (modeStr.equals("CEILING")) {
        mode = RoundingMode.CEILING;
    } else if (modeStr.equals("HALF_UP")) {
        mode = RoundingMode.HALF_UP;
    } else {
        throw new RuntimeException(
                type + " defined in the config file is not CEILING, FLOOR, HALF_UP. It is " + modeStr);
    }
    return mode;
}

From source file:com.grarak.kerneladiutor.utils.Utils.java

public static double roundTo2Decimals(double val) {
    BigDecimal bd = new BigDecimal(val);
    bd = bd.setScale(2, RoundingMode.HALF_UP);
    return bd.doubleValue();
}