Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

In this page you can find the example usage for java.math BigDecimal ROUND_HALF_UP.

Prototype

int ROUND_HALF_UP

To view the source code for java.math BigDecimal ROUND_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.kalypso.zml.core.table.binding.rule.instructions.ZmlMetadataBoundaryInstruction.java

@Override
public boolean matches(final IZmlModelCell reference) throws SensorException {
    if (!(reference instanceof IZmlModelValueCell))
        return false;

    final IZmlModelValueCell cell = (IZmlModelValueCell) reference;

    final MetadataBoundary metaFrom = getBoundaryFrom(cell);
    final MetadataBoundary metaTo = getBoundaryTo(cell);
    if (Objects.allNull(metaFrom, metaTo))
        return false;

    final String boundaryType = findBoundaryType(metaFrom, metaTo);

    final double value = findValue(cell, boundaryType);
    if (Double.isNaN(value))
        return false;

    // FIXME: get the scale from the axis and/or table column definition
    final int scale = 3;
    final BigDecimal valueDecimal = new BigDecimal(value).setScale(scale, BigDecimal.ROUND_HALF_UP);

    if (!compareMeta(metaFrom, getType().getFrom(), valueDecimal, getType().getOpFrom()))
        return false;
    if (!compareMeta(metaTo, getType().getTo(), valueDecimal, getType().getOpTo()))
        return false;

    return true;/*  w w  w. j  a v a  2s .  c o  m*/
}

From source file:co.nubetech.apache.hadoop.BigDecimalSplitter.java

/**
 * Divide numerator by denominator. If impossible in exact mode, use
 * rounding.//w w  w. j a  v a 2s  .  c  o  m
 */
protected BigDecimal tryDivide(BigDecimal numerator, BigDecimal denominator) {
    try {
        return numerator.divide(denominator);
    } catch (ArithmeticException ae) {
        return numerator.divide(denominator, BigDecimal.ROUND_HALF_UP);
    }
}

From source file:nl.b3p.kaartenbalie.core.server.accounting.entity.Transaction.java

public void validate() throws TransactionDeniedException {
    if (getCreditAlteration().doubleValue() < 0) {
        throw new TransactionDeniedException("Transaction creditalteration cannot be less then zero.");
    }/*from ww w .  j a v a2s.  com*/
    //Scale the creditAlteration...
    setCreditAlteration(getCreditAlteration().setScale(2, BigDecimal.ROUND_HALF_UP));

    if (billingAmount != null && billingAmount.doubleValue() > 9999) {
        log.error("Billingamount larger then 9999.");
        throw new TransactionDeniedException("Billingamount larger then 9999.");
    }
    if (getType() != WITHDRAW && getType() != DEPOSIT) {
        log.error("Only DEPOSIT or WITHDRAW is allowed for this transaction.");
        throw new TransactionDeniedException("Only DEPOSIT or WITHDRAW is allowed for this transaction.");
    }
}

From source file:net.certiv.authmgr.task.section.model.AnalyzeModel.java

private void analyzeWords(String category, String partition, HashMap<String, WordProbabilityPT> wordsMap) {

    // convert to sorted set
    WordProbPTComparator sorter = new WordProbPTComparator();
    TreeSet<WordProbabilityPT> wordProbs = new TreeSet<WordProbabilityPT>(sorter);
    wordProbs.addAll(wordsMap.values());

    // now accumulate and print statistics
    StringBuffer wordlist = new StringBuffer();
    int k = 0;/* w  ww.ja  v  a2 s . c o  m*/
    for (Iterator<WordProbabilityPT> it = wordProbs.iterator(); it.hasNext() && k < 20; k++) {
        WordProbabilityPT wp = it.next();
        String word = wp.getWord();
        double prob = wp.getProbability();
        double count = wp.getMatchingCount();

        BigDecimal probBD = new BigDecimal(prob).setScale(8, BigDecimal.ROUND_HALF_UP);
        String countStr = Util.rightAlign("" + count, 6);
        String wordAbbr = StringUtils.abbreviate(word, 13);
        wordlist.append(Util.leftAlign(wordAbbr, 14) + probBD + "/" + countStr + "| ");
    }
    Log.info(this, Util.leftAlign(partition + ":", 14) + Util.rightAlign("" + wordProbs.size(), 5) + " = "
            + wordlist.toString());
}

From source file:com.gm.machine.util.CommonUtils.java

/**
 * ?????/* ww w  .j a  v a2 s.com*/
 * 
 * @param a
 * @return
 */
public static double getDecimal(double a) {
    BigDecimal bd = new BigDecimal(a);
    bd = bd.setScale(3, BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
}

From source file:com.taobao.adfs.database.tdhsocket.client.util.ConvertUtil.java

public static BigDecimal getBigDecimalFromString(String stringVal, int scale) throws SQLException {
    BigDecimal bdVal;/*from   w w  w .ja  va2  s  . c  o m*/

    if (stringVal != null) {
        if (stringVal.length() == 0) {
            bdVal = new BigDecimal("0");
            try {
                return bdVal.setScale(scale);
            } catch (ArithmeticException ex) {
                try {
                    return bdVal.setScale(scale, BigDecimal.ROUND_HALF_UP);
                } catch (ArithmeticException arEx) {
                    throw new SQLException(
                            "ResultSet.Bad_format_for_BigDecimal: value=" + stringVal + ",scale=" + scale);
                }
            }
        }
        try {
            try {
                return new BigDecimal(stringVal).setScale(scale);
            } catch (ArithmeticException ex) {
                try {
                    return new BigDecimal(stringVal).setScale(scale, BigDecimal.ROUND_HALF_UP);
                } catch (ArithmeticException arEx) {
                    throw new SQLException(
                            "ResultSet.Bad_format_for_BigDecimal: value=" + stringVal + ",scale=" + scale);
                }
            }
        } catch (NumberFormatException ex) {
            throw new SQLException(
                    "ResultSet.Bad_format_for_BigDecimal: value=" + stringVal + ",scale=" + scale);
        }
    }

    return null;
}

From source file:net.sourceforge.fenixedu.domain.credits.util.DepartmentCreditsPoolBean.java

protected void setValues() {
    departmentSharedExecutionCourses = new TreeSet<DepartmentExecutionCourse>();
    departmentExecutionCourses = new TreeSet<DepartmentExecutionCourse>();
    otherDepartmentSharedExecutionCourses = new TreeSet<DepartmentExecutionCourse>();
    availableCredits = BigDecimal.ZERO;
    assignedCredits = BigDecimal.ZERO;
    if (departmentCreditsPool != null) {
        for (ExecutionSemester executionSemester : getAnnualCreditsState().getExecutionYear()
                .getExecutionPeriodsSet()) {
            for (ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) {
                if (!(executionCourse.isDissertation() || executionCourse.getProjectTutorialCourse())) {
                    if (executionCourse.getDepartments().contains(getDepartment())) {
                        if (isSharedExecutionCourse(executionCourse)) {
                            addToSet(departmentSharedExecutionCourses, executionCourse);
                        } else {
                            addToSet(departmentExecutionCourses, executionCourse);
                        }/*from w w w . j a  va  2 s .c  o m*/
                    } else if (isTaughtByTeacherFromThisDepartment(executionCourse)) {
                        addToSet(otherDepartmentSharedExecutionCourses, executionCourse);
                    }
                }
            }
        }
        assignedCredits = assignedCredits.setScale(2, BigDecimal.ROUND_HALF_UP);
        availableCredits = departmentCreditsPool.getCreditsPool().subtract(assignedCredits).setScale(2,
                BigDecimal.ROUND_HALF_UP);
    }
}

From source file:morphy.utils.MorphyStringUtils.java

/**
 * Returns the value specified in bytes into megs. Currently only shows 2
 * digits after the decimal and rounds half up.
 *//*from w w  w  .ja  va  2 s.c o  m*/
public static String getMegs(long bytes) {
    BigDecimal bigDecimal = new BigDecimal(bytes / 1048576.0);
    bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
    return bigDecimal.toString() + "Megs";
}

From source file:org.egov.ptis.web.controller.reports.DailyCollectionReportAdaptor.java

@Override
public JsonElement serialize(DailyCollectionReportResult dailyCollectionReportResult, Type typeOfSrc,
        JsonSerializationContext context) {
    JsonObject jsonObject = new JsonObject();
    final SimpleDateFormat receiptDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
    jsonObject.addProperty("receiptNo", dailyCollectionReportResult.getReceiptNumber());
    jsonObject.addProperty("receiptDate",
            receiptDateFormatter.format(dailyCollectionReportResult.getReceiptDate()));
    jsonObject.addProperty("assessmentNumber", dailyCollectionReportResult.getAssessmentNumber());
    jsonObject.addProperty("ownerName", dailyCollectionReportResult.getOwnerName());
    jsonObject.addProperty("doorNumber",
            StringUtils.isNotBlank(dailyCollectionReportResult.getDoorNumber())
                    ? dailyCollectionReportResult.getDoorNumber()
                    : "N/A");
    jsonObject.addProperty("paidAt", dailyCollectionReportResult.getPaidAt());
    jsonObject.addProperty("paymentMode", dailyCollectionReportResult.getPaymentMode());
    jsonObject.addProperty("status", dailyCollectionReportResult.getStatus());
    jsonObject.addProperty("fromDate", dailyCollectionReportResult.getFromInstallment());
    jsonObject.addProperty("toDate", dailyCollectionReportResult.getToInstallment());
    jsonObject.addProperty("arrearAmt",
            null != dailyCollectionReportResult.getArrearAmount()
                    ? dailyCollectionReportResult.getArrearAmount().setScale(2, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO);
    jsonObject.addProperty("currAmt",
            null != dailyCollectionReportResult.getCurrentAmount()
                    ? dailyCollectionReportResult.getCurrentAmount().setScale(2, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO);
    jsonObject.addProperty("totalPenalty",
            null != dailyCollectionReportResult.getTotalPenalty()
                    ? dailyCollectionReportResult.getTotalPenalty().setScale(2, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO);
    jsonObject.addProperty("arrearLibCess",
            null != dailyCollectionReportResult.getArrearLibCess()
                    ? dailyCollectionReportResult.getArrearLibCess().setScale(2, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO);
    jsonObject.addProperty("currLibCess",
            null != dailyCollectionReportResult.getCurrentLibCess()
                    ? dailyCollectionReportResult.getCurrentLibCess().setScale(2, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO);
    jsonObject.addProperty("totalLibCess",
            null != dailyCollectionReportResult.getTotalLibCess()
                    ? dailyCollectionReportResult.getTotalLibCess().setScale(2, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO);
    jsonObject.addProperty("totalCollection",
            dailyCollectionReportResult.getTotalCollection().setScale(2, BigDecimal.ROUND_HALF_UP));
    jsonObject.addProperty("totalRebate",
            dailyCollectionReportResult.getTotalRebate().setScale(2, BigDecimal.ROUND_HALF_UP));
    jsonObject.addProperty("ward", dailyCollectionReportResult.getWard());
    return jsonObject;
}

From source file:com.guodong.sun.guodong.uitls.CacheUtil.java

public static String getFormatSize(double size) {
    double kiloByte = size / 1024;
    if (kiloByte < 1) {
        //            return size + "Byte";
        return "0K";
    }/*from   w  w w .  j a  v a  2  s  .com*/

    double megaByte = kiloByte / 1024;
    if (megaByte < 1) {
        BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
        return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
    }

    double gigaByte = megaByte / 1024;
    if (gigaByte < 1) {
        BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
        return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
    }

    double teraBytes = gigaByte / 1024;
    if (teraBytes < 1) {
        BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
        return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
    }
    BigDecimal result4 = new BigDecimal(teraBytes);
    return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
}