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.cirdles.ambapo.UTMToLatLong.java

/**
 * Calculates the xi-north which refers to the north-south direction of the UTM.
 * @param hemisphere// w w w  .j  av a2 s  .  co m
 * @param meridianRadius
 * @param northing
 * @return xi north
 */
private static BigDecimal calcXiNorth(char hemisphere, BigDecimal meridianRadius, BigDecimal northing) {

    BigDecimal xiNorth;

    if (hemisphere == 'N') {

        BigDecimal divideByThis = SCALE_FACTOR.multiply(meridianRadius).setScale(PRECISION,
                RoundingMode.HALF_UP);

        xiNorth = northing.divide(divideByThis, PRECISION, RoundingMode.HALF_UP);

    }

    else {

        BigDecimal numerator = (new BigDecimal(10000000)).subtract(northing);
        BigDecimal denominator = SCALE_FACTOR.multiply(meridianRadius);

        xiNorth = numerator.divide(denominator, PRECISION, RoundingMode.HALF_UP);

    }

    return xiNorth;

}

From source file:com.mitchellbosecke.pebble.spring.PebbleView.java

@Override
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    response.setCharacterEncoding(this.characterEncoding);

    long startNanos = System.nanoTime();

    PebbleTemplate template = this.engine.getTemplate(this.templateName);

    // Add beans context
    model.put(BEANS_VARIABLE_NAME, new Beans(this.getApplicationContext()));

    // Add request & response
    model.put(REQUEST_VARIABLE_NAME, request);
    model.put(RESPONSE_VARIABLE_NAME, response);

    // Add session
    model.put(SESSION_VARIABLE_NAME, request.getSession(false));

    // Locale/*from  ww w  .  j av  a 2  s.  c  o  m*/
    Locale locale = RequestContextUtils.getLocale(request);

    final Writer writer = response.getWriter();
    try {
        template.evaluate(writer, model, locale);
    } finally {
        writer.flush();
    }

    if (TIMER_LOGGER.isDebugEnabled()) {
        long endNanos = System.nanoTime();

        BigDecimal elapsed = BigDecimal.valueOf(endNanos - startNanos);
        BigDecimal elapsedMs = elapsed.divide(BigDecimal.valueOf(NANOS_IN_SECOND), RoundingMode.HALF_UP);
        TIMER_LOGGER.debug("Pebble template \"{}\" with locale {} processed in {} nanoseconds (approx. {}ms)",
                new Object[] { this.templateName, locale, elapsed, elapsedMs });
    }
}

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

private ResourcesPerDay(BigDecimal amount) {
    Validate.isTrue(amount.intValue() >= 0);
    this.amount = amount.setScale(4, RoundingMode.HALF_UP);
}

From source file:tagtime.beeminder.BeeminderGraph.java

/**
 * Parses a graph's data and sets up a .bee file to track which tags
 * have been submitted to the graph./*from w w w .jav  a 2  s. c  o m*/
 * @param username The user's Beeminder username.
 * @param dataEntry The data entry for the current graph. This must
 *            be in the format "graphName|tags".
 */
public BeeminderGraph(TagTime tagTimeInstance, String username, String dataEntry) {
    if (username == null || dataEntry == null) {
        throw new IllegalArgumentException(
                "Both parameters to the " + "BeeminderGraphData constructor must be defined.");
    }

    this.tagTimeInstance = tagTimeInstance;

    int decimalDigits = tagTimeInstance.settings.getIntValue(SettingType.PRECISION);
    hourFormatter = new DecimalFormat();
    hourFormatter.setGroupingUsed(false);
    hourFormatter.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.US));
    hourFormatter.setRoundingMode(RoundingMode.HALF_UP);
    hourFormatter.setMaximumFractionDigits(decimalDigits);
    roundingMultiplier = (int) Math.pow(10, decimalDigits);

    //find the graph name
    int graphDelim = dataEntry.indexOf('|');
    if (graphDelim < 0 || graphDelim >= dataEntry.length() - 1) {
        throw new IllegalArgumentException("dataEntry must be in " + "format \"graphname|tags\"");
    }
    graphName = dataEntry.substring(0, graphDelim);

    //get the tags
    String[] tags = dataEntry.substring(graphDelim + 1).split("\\s+");

    List<String> acceptedTags = new ArrayList<String>(3);
    List<String> rejectedTags = new ArrayList<String>(0);

    //enter the tags in the correct lists
    for (String tag : tags) {
        if (tag.charAt(0) == '-') {
            rejectedTags.add(tag.substring(1).toLowerCase());
        } else {
            acceptedTags.add(tag.toLowerCase());
        }
    }

    //make sure some tags were entered
    if (acceptedTags.size() == 0 && rejectedTags.size() == 0) {
        throw new IllegalArgumentException("No tags provided.");
    }

    tagMatcher = new TagMatcher(acceptedTags, rejectedTags);
}

From source file:org.apache.niolex.commons.codec.IntegerUtil.java

/**
 * Format the size into string end with one letter. We will round the result
 * by half up, and keep two decimal places.
 *
 * @param size the size need to be formatted
 * @return the string representation/*from  w  ww.j  a v  a 2 s . c  om*/
 */
public static final String formatSize(double size) {
    DecimalFormat df = new DecimalFormat("#,###.##");
    df.setRoundingMode(RoundingMode.HALF_UP);
    if (size >= Const.T) {
        return df.format(size / Const.T) + "T";
    }
    if (size >= Const.G) {
        return df.format(size / Const.G) + "G";
    }
    if (size >= Const.M) {
        return df.format(size / Const.M) + "M";
    }
    if (size >= Const.K) {
        return df.format(size / Const.K) + "K";
    }
    return df.format(size);
}

From source file:me.smoe.adar.utils.cam.o.mapping.CAMatcher.java

private static Integer calcCumulateScore(int old, int cur) {
    return new BigDecimal(10000).subtract(new BigDecimal(old))
            .divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(cur))
            .add(new BigDecimal(old)).intValue();
}

From source file:com.zte.ums.zenap.itm.agent.plugin.linux.util.Calculator.java

public String calculateItem(Map variables, String formula) throws MonitorException {

    Set vKeySet = variables.keySet();
    Object[] keys = vKeySet.toArray();
    Arrays.sort(keys);/* w  w w  .j av  a2  s .  com*/
    JexlContext jexlContext = new MapContext();
    for (int i = keys.length - 1; i >= 0; i--) {
        String s = keys[i].toString();
        String s1 = s.replace('.', 'a');
        formula = formula.replaceAll(s, s1);
        jexlContext.set(s1, variables.get(s));
    }

    try {
        while (true) {
            int eIndex = formula.indexOf("E");
            if (eIndex == -1) {
                break;
            }
            int startIndex = getBackwardNumIndex(formula, eIndex);
            int endIndex = getForwardNumIndex(formula, eIndex);
            String eNum = formula.substring(eIndex + 1, endIndex);
            String tenNumString = null;
            int num = Integer.parseInt(eNum);
            if (num > 5) {
                int tenNum = 1;
                for (int i = 0; i < (num - 5); i++) {
                    tenNum = tenNum * 10;
                }
                tenNumString = "100000.0 * " + Integer.toString(tenNum);
            } else if (num > 0) {
                int tenNum = 1;
                for (int i = 0; i < num; i++) {
                    tenNum = tenNum * 10;
                }
                tenNumString = Integer.toString(tenNum);
            } else if (num < 0) {
                double tenNum = 1;
                for (int i = 0; i > num; i--) {
                    tenNum = tenNum * 0.1;
                }
                tenNumString = Double.toString(tenNum);
            }
            String variable = formula.substring(startIndex, endIndex);
            String headVariable = formula.substring(startIndex, eIndex);
            formula = formula.replaceFirst(variable, "(" + headVariable + " * " + tenNumString + ")");
        }
        JexlEngine jexlEngine = new JexlEngine();
        Expression expression = jexlEngine.createExpression(formula);
        Object result = expression.evaluate(jexlContext);
        if (result instanceof Double) {
            Double dd = (Double) result;

            NumberFormat formater = new DecimalFormat("#.00");
            formater.setRoundingMode(RoundingMode.HALF_UP);
            return formater.format(dd);
        }
        return result.toString();
    } catch (Exception e) {
        throw new MonitorException("Error!Something wrong happened! ", e);
    }
}

From source file:tibano.service.ParkService.java

@RequestMapping(path = "/getPaymentInfo")
PaymentInfo getPaymentInfo(@RequestParam(name = "areaId") Long areaId,
        @RequestParam(name = "licensePlate") String licensePlate) {
    ParkingTransaction pt = ptRepository.findOpenTransactionByAreaAndLicensePlate(areaId, licensePlate);
    if (pt != null) {
        Duration duration = Duration.between(pt.getStart(), LocalDateTime.now());
        Double amount = duration.getSeconds() * SEC_TARIF;
        BigDecimal bd = new BigDecimal(amount);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        Integer loyaltyPoints = 5 + Integer.valueOf(Double.valueOf(bd.doubleValue()).intValue());
        return new PaymentInfo(pt.getEnd(), amount, duration, loyaltyPoints);
    }/*from  www.j a  v a2s.  co m*/
    return new PaymentInfo(null, Double.valueOf(0), Duration.ZERO, Integer.valueOf(0));
}

From source file:com.etiansoft.haier.service.ManagerService.java

/**
 * //from   w  w w .j av a2  s  . com
 * @Title: ???
 * @Description: TODO
 * @param @param page
 * @param @param name
 * @param @param phone
 * @param @param status
 * @param @return
 * @param @throws Exception
 * @return DataTablePage
 * @throws
 */
public DataTablePage getData(DataTablePage page, String name, String phone, String status, String merchant_num,
        String order_id) throws Exception {
    DataTablePage dataTable = null;

    dataTable = udsService.findPage(page, Merchant.class, MerchantVo.class, tableName, "create_date", "desc",
            makeParam(name, phone, status, merchant_num));

    List<MerchantVo> datas = (List<MerchantVo>) dataTable.getAaData();

    for (MerchantVo dataMerchant : datas) {
        Map<String, Object> mapm = new HashMap<String, Object>();
        mapm.put("merchant_id", dataMerchant.getMerchantId());
        List<Order> listm = (List<Order>) udsService.findByTimeForOrder2("order", Order.class, mapm);

        BigDecimal num = new BigDecimal(0);

        if (listm != null && listm.size() > 0) {
            for (Order or : listm) {
                if (or.getStatus().intValue() == 2 || or.getStatus().intValue() == 3
                        || or.getStatus().intValue() == 4 || or.getStatus().intValue() == 5) {
                    num = num.add(new BigDecimal(or.getFavored_amount()).add(new BigDecimal(or.getFreight())));
                }
            }
        }
        dataMerchant.setSaleVolum(num.setScale(2, RoundingMode.HALF_UP).doubleValue());
        Mpromotion promotion = (Mpromotion) udsService.findById("mpromotion", "merchant_id_",
                dataMerchant.getMerchantId(), Mpromotion.class);
        if (promotion != null) {
            dataMerchant.setPromotion_sort(promotion.getSort());
            dataMerchant.setPromotion_tag(promotion.getPromotion_tag());
        }

    }

    return dataTable;

}

From source file:org.kalypso.model.wspm.core.profil.util.ProfileUtil.java

/**
 * Converts a double valued station into a BigDecimal with a scale of {@value #STATION_SCALE}.
 *
 * @see #STATION_SCALE//w  w w  .  j ava  2s  .  c o m
 */
public static BigDecimal stationToBigDecimal(final double station) {
    return new BigDecimal(station).setScale(IProfileFeature.STATION_SCALE, RoundingMode.HALF_UP);
}