Example usage for java.math BigDecimal ROUND_HALF_EVEN

List of usage examples for java.math BigDecimal ROUND_HALF_EVEN

Introduction

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

Prototype

int ROUND_HALF_EVEN

To view the source code for java.math BigDecimal ROUND_HALF_EVEN.

Click Source Link

Document

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

Usage

From source file:org.kuali.kpme.core.earncode.service.EarnCodeServiceImpl.java

@Override
public BigDecimal roundHrsWithEarnCode(BigDecimal hours, EarnCodeContract earnCode) {
    String roundOption = HrConstants.ROUND_OPTION_MAP.get(earnCode.getRoundingOption());
    BigDecimal fractScale = new BigDecimal(earnCode.getFractionalTimeAllowed());
    if (roundOption == null) {
        LOG.error("Rounding option of Earn Code " + earnCode.getEarnCode() + " is not recognized.");
        return null;
        //         throw new RuntimeException("Rounding option of Earn Code " + earnCode.getEarnCode() + " is not recognized.");
    }//from   w w  w  .j  ava 2 s  . co m
    BigDecimal roundedHours = hours;
    if (roundOption.equals("Traditional")) {
        roundedHours = hours.setScale(fractScale.scale(), BigDecimal.ROUND_HALF_EVEN);
    } else if (roundOption.equals("Truncate")) {
        roundedHours = hours.setScale(fractScale.scale(), BigDecimal.ROUND_DOWN);
    }
    return roundedHours;
}

From source file:Armadillo.Analytics.Base.Precision.java

/**
 * Rounds the given non-negative value to the "nearest" integer. Nearest is
 * determined by the rounding method specified. Rounding methods are defined
 * in {@link BigDecimal}./*from  w w  w .  jav a2s  .c om*/
 *
 * @param unscaled Value to round.
 * @param sign Sign of the original, scaled value.
 * @param roundingMethod Rounding method, as defined in {@link BigDecimal}.
 * @return the rounded value.
 * @throws MathArithmeticException if an exact operation is required but result is not exact
 * @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method.
 * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
 */
private static double roundUnscaled(double unscaled, double sign, int roundingMethod)
        throws MathArithmeticException, MathIllegalArgumentException {
    switch (roundingMethod) {
    case BigDecimal.ROUND_CEILING:
        if (sign == -1) {
            unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        } else {
            unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        }
        break;
    case BigDecimal.ROUND_DOWN:
        unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        break;
    case BigDecimal.ROUND_FLOOR:
        if (sign == -1) {
            unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        } else {
            unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        }
        break;
    case BigDecimal.ROUND_HALF_DOWN: {
        unscaled = FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY);
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction > 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else {
            unscaled = FastMath.floor(unscaled);
        }
        break;
    }
    case BigDecimal.ROUND_HALF_EVEN: {
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction > 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else if (fraction < 0.5) {
            unscaled = FastMath.floor(unscaled);
        } else {
            // The following equality test is intentional and needed for rounding purposes
            if (FastMath.floor(unscaled) / 2.0 == FastMath.floor(Math.floor(unscaled) / 2.0)) { // even
                unscaled = FastMath.floor(unscaled);
            } else { // odd
                unscaled = FastMath.ceil(unscaled);
            }
        }
        break;
    }
    case BigDecimal.ROUND_HALF_UP: {
        unscaled = FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY);
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction >= 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else {
            unscaled = FastMath.floor(unscaled);
        }
        break;
    }
    case BigDecimal.ROUND_UNNECESSARY:
        if (unscaled != FastMath.floor(unscaled)) {
            throw new MathArithmeticException();
        }
        break;
    case BigDecimal.ROUND_UP:
        unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        break;
    default:
        throw new MathIllegalArgumentException(LocalizedFormats.INVALID_ROUNDING_METHOD, roundingMethod,
                "ROUND_CEILING", BigDecimal.ROUND_CEILING, "ROUND_DOWN", BigDecimal.ROUND_DOWN, "ROUND_FLOOR",
                BigDecimal.ROUND_FLOOR, "ROUND_HALF_DOWN", BigDecimal.ROUND_HALF_DOWN, "ROUND_HALF_EVEN",
                BigDecimal.ROUND_HALF_EVEN, "ROUND_HALF_UP", BigDecimal.ROUND_HALF_UP, "ROUND_UNNECESSARY",
                BigDecimal.ROUND_UNNECESSARY, "ROUND_UP", BigDecimal.ROUND_UP);
    }
    return unscaled;
}

From source file:com.zl.bgec.basicapi.shop.service.impl.ShopServiceImpl.java

@Override
@Transactional(readOnly = true)//from   w w w. j a  v a2  s  .  c  o  m
public Map<String, Object> getShopIndexInfo(String memberNo) throws Exception {
    String sql = "select tsi.shop_name shopName," + "tsi.shop_address shopAddress," + "tsi.shop_logo shopLogo,"
            + "tsi.status status, " + "tsi.shop_no shopNo "
            + "from tbl_shop_info tsi where tsi.merch_no=:shopNo and tsi.status!='3'";
    Query query = shopDao.createSQLQuery(sql);
    query.setParameter("shopNo", memberNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> results = query.list();
    Map<String, Object> result = new HashMap<String, Object>();
    if (results != null && !results.isEmpty()) {
        result = results.get(0);
    } else {
        return null;
    }
    String shopNo = String.valueOf(result.get("shopNo"));
    Criteria criteria = commodityDao.createCriteria(Restrictions.eq("sellerNo", shopNo));
    criteria.add(Restrictions.eq("deleteFlag", (byte) 0));//
    criteria.add(Restrictions.eq("publishState", "1"));//
    int commodityCount = commodityDao.getRowCount(criteria);// ??
    result.put("commodityCount", String.valueOf(commodityCount));
    criteria = shopCollectDao.createCriteria(Restrictions.eq("shopNo", shopNo));
    int collectCount = shopCollectDao.getRowCount(criteria);
    result.put("collectCount", String.valueOf(collectCount));
    Criteria promotionCriteria = promotionDao.createCriteria(Restrictions.eq("shopNo", shopNo));
    promotionCriteria.add(Restrictions.ge("endTime", new Date()));//
    promotionCriteria.add(Restrictions.eq("status", "2"));//
    promotionCriteria.add(Restrictions.eq("lockFlag", "0"));//?
    promotionCriteria.add(Restrictions.ne("promotionType", "2"));//?
    int count = promotionDao.getRowCount(promotionCriteria);
    result.put("promotionCount", count);
    List<String> values = new ArrayList<String>();
    //      values.add(OrderConstants.BASIC_STATE_REFUND);
    //      values.add(OrderConstants.BASIC_STATE_ALREADY_RECEIVE);
    //      values.add(OrderConstants.BASIC_STATE_REFUND_APPLY);
    values.add(OrderConstants.BASIC_STATE_WAITING_DELIVERY);
    //      values.add(OrderConstants.BASIC_STATE_WAITING_RETURN);
    //      values.add(OrderConstants.BASIC_STATE_WAITING_PAY);
    //      values.add(OrderConstants.BASIC_STATE_ALREADY_DELIVERY);
    Criteria criteriaOrder = orderDao.createCriteria(Restrictions.in("basicState", values));
    criteriaOrder.add(Restrictions.eq("deleteFlag", (byte) 0));
    criteriaOrder.add(Restrictions.eq("shopNo", shopNo));
    String sqlGroupBuy = "select count(*) " + "  from tbl_promotion tp "
            + " left join tbl_product tpr on tp.ref_commo_no = tpr.commo_no"
            + " where tp.promotion_type='2' and tp.delete_flag='0' and tp.shop_no=:shopNo  and :curentTime between tp.start_time and tp.end_time ";
    Query groupBuyQuery = promotionDao.createSQLQuery(sqlGroupBuy);
    groupBuyQuery.setParameter("shopNo", shopNo);
    groupBuyQuery.setParameter("curentTime", new Date());
    BigInteger totalRows = (BigInteger) groupBuyQuery.uniqueResult();
    result.put("groupBuyCount", totalRows.intValue());
    result.put("orderCount", orderDao.getRowCount(criteriaOrder));
    String gradeSql = "select  avg(tcc.service_grade) serviceGrade," + " avg(tcc.delivery_grade) deliveryGrade"
            + " from tbl_commodity_comment tcc " + " where tcc.shop_no = :shopNo " + " group by(tcc.shop_no) ";
    Query queryGrade = shopDao.createSQLQuery(gradeSql);
    queryGrade.setParameter("shopNo", shopNo);
    queryGrade.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> list = queryGrade.list();
    if (list != null && !list.isEmpty()) {
        Double servGrade = list.get(0).get("serviceGrade") == null ? 0
                : Double.valueOf(list.get(0).get("serviceGrade").toString());
        BigDecimal serviceGrade = new BigDecimal(servGrade);
        serviceGrade = serviceGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
        result.put("serviceGrade", serviceGrade.doubleValue());
        Double delGrade = list.get(0).get("deliveryGrade") == null ? 0
                : Double.valueOf(list.get(0).get("deliveryGrade").toString());
        BigDecimal deliveryGrade = new BigDecimal(delGrade);
        deliveryGrade = deliveryGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
        result.put("deliveryGrade", deliveryGrade.doubleValue());
    } else {
        result.put("serviceGrade", "0");
        result.put("deliveryGrade", "0");
    }

    return result;
}

From source file:uk.ac.leeds.ccg.andyt.projects.moses.process.Comparison.java

public void compareCASUV003WithCAS001() throws Exception {
    File infile;/*w  ww .  ja  v  a2s  .  c o  m*/
    infile = new File("C:/Work/Projects/MoSeS/Workspace/UV003.dat");
    CASUV003DataHandler cASUV003DataHandler = new CASUV003DataHandler(infile);
    infile = new File("C:/Work/Projects/MoSeS/Workspace/CAS001.dat");
    CAS001DataHandler tCAS001DataHandler = new CAS001DataHandler(infile);

    CASUV003DataRecord aCASUV003DataRecord;
    CAS001DataRecord aCAS001DataRecord;
    long difference;
    long maxDifference = Long.MIN_VALUE;
    long sumOfSquaredDifference = 0L;
    long totalDifference = 0L;
    long absoluteDifference = 0L;
    long totalAbsoluteDifference = 0L;
    long RecordID;
    long nRecords = cASUV003DataHandler.getNDataRecords();
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        difference = (long) (aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        if (difference < 0) {
            absoluteDifference = difference * -1L;
        }
        sumOfSquaredDifference += (difference * difference);
        maxDifference = Math.max(maxDifference, difference);
        totalDifference += difference;
        totalAbsoluteDifference += absoluteDifference;
    }
    int scale = 100;
    int roundingMode = BigDecimal.ROUND_HALF_EVEN;
    BigDecimal nRecordsBigDecimal = new BigDecimal(nRecords);
    BigDecimal meanDifferenceBigDecimal = new BigDecimal(maxDifference).divide(nRecordsBigDecimal, scale,
            roundingMode);
    System.out.println("nRecords " + nRecords);
    System.out.println("meanDifferenceBigDecimal " + meanDifferenceBigDecimal.toString());
    System.out.println("sumOfSquaredDifference " + sumOfSquaredDifference);
    System.out.println("maxDifference " + maxDifference);
    System.out.println("totalAbsoluteDifference " + totalAbsoluteDifference);
    System.out.println("totalDifference " + totalDifference);
    BigDecimal standardDeviationOfDifferenceBigDecimal = new BigDecimal("0");
    BigDecimal differenceBigDecimal;
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        differenceBigDecimal = new BigDecimal(
                aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        standardDeviationOfDifferenceBigDecimal = differenceBigDecimal.multiply(differenceBigDecimal);
    }
    standardDeviationOfDifferenceBigDecimal = standardDeviationOfDifferenceBigDecimal
            .divide(nRecordsBigDecimal.subtract(BigDecimal.ONE), scale, roundingMode);
    standardDeviationOfDifferenceBigDecimal = Generic_BigDecimal.sqrt(standardDeviationOfDifferenceBigDecimal,
            scale, RoundingMode.HALF_EVEN);
    System.out.println("standardDeviationOfDifferenceBigDecimal " + standardDeviationOfDifferenceBigDecimal);
}

From source file:com.abiquo.api.services.cloud.VirtualApplianceService.java

@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
private Map<VirtualMachineCost, BigDecimal> addVirtualMachineCost(
        final Map<VirtualMachineCost, BigDecimal> virtualMachinesCost, final VirtualMachine virtualMachine,
        final VirtualMachineRequirements virtualMachineRequirements, final PricingTemplate pricingTemplate) {
    BigDecimal BYTES_TO_GB = new BigDecimal(1024l * 1024l * 1024l);
    BigDecimal MB_TO_GB = new BigDecimal(1024);
    getCostCodeCost(virtualMachinesCost, virtualMachine, pricingTemplate);

    Collection<RasdManagement> resources = rasdManDao.findByVirtualMachine(virtualMachine);
    getAdditionalStorageCost(virtualMachinesCost, resources, pricingTemplate);

    virtualMachinesCost.put(VirtualMachineCost.COMPUTE, virtualMachinesCost.get(VirtualMachineCost.COMPUTE)
            .add(pricingTemplate.getVcpu().multiply(new BigDecimal(virtualMachineRequirements.getCpu()))));
    virtualMachinesCost.put(VirtualMachineCost.COMPUTE,
            virtualMachinesCost.get(VirtualMachineCost.COMPUTE).add(pricingTemplate.getMemoryGB()
                    .multiply(new BigDecimal(virtualMachineRequirements.getRam()).divide(MB_TO_GB))));

    virtualMachinesCost.put(VirtualMachineCost.STORAGE,
            virtualMachinesCost.get(VirtualMachineCost.STORAGE)
                    .add(pricingTemplate.getHdGB().multiply(new BigDecimal(virtualMachineRequirements.getHd())
                            .divide(BYTES_TO_GB, 2, BigDecimal.ROUND_HALF_EVEN))));

    virtualMachinesCost.put(VirtualMachineCost.NETWORK, virtualMachinesCost.get(VirtualMachineCost.NETWORK).add(
            pricingTemplate.getPublicIp().multiply(new BigDecimal(virtualMachineRequirements.getPublicIP()))));

    virtualMachinesCost.put(VirtualMachineCost.TOTAL,
            virtualMachinesCost.get(VirtualMachineCost.COST_CODE)
                    .add(virtualMachinesCost.get(VirtualMachineCost.COMPUTE)
                            .add(virtualMachinesCost.get(VirtualMachineCost.STORAGE)
                                    .add(virtualMachinesCost.get(VirtualMachineCost.ADDITIONAL_VOLUME)
                                            .add(virtualMachinesCost.get(VirtualMachineCost.NETWORK))))));
    return virtualMachinesCost;
}

From source file:ru.tinkoff.acquiring.sdk.EnterCardFragment.java

private String getFormattedPrice() {
    Intent intent = getActivity().getIntent();
    Money money = (Money) intent.getSerializableExtra(PayFormActivity.EXTRA_AMOUNT);
    BigDecimal bigDecimal = new BigDecimal(money.getCoins());
    bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    return bigDecimal.toString();
}

From source file:org.egov.egf.web.actions.report.VoucherStatusReportAction.java

private void populateData() throws ApplicationException {
    final List<CVoucherHeader> list = new ArrayList();
    list.addAll(voucherSearchQuery().list());
    BigDecimal amt = BigDecimal.ZERO;
    for (final CVoucherHeader cVchrHdr : list) {
        final VoucherReportView vhcrRptView = new VoucherReportView();
        vhcrRptView.setDeptName(cVchrHdr.getVouchermis().getDepartmentid().getName());
        vhcrRptView.setVoucherNumber(cVchrHdr.getVoucherNumber());
        vhcrRptView.setVoucherType(cVchrHdr.getType());
        vhcrRptView.setVoucherName(cVchrHdr.getName());
        vhcrRptView.setVoucherDate(cVchrHdr.getVoucherDate());
        vhcrRptView.setSource(getVoucherModule(cVchrHdr.getModuleId()));
        for (final CGeneralLedger detail : cVchrHdr.getGeneralledger())
            amt = amt.add(BigDecimal.valueOf(detail.getDebitAmount()).setScale(2, BigDecimal.ROUND_HALF_EVEN));
        vhcrRptView.setAmount(amt);/*from   w w  w  .ja va2s . c o m*/
        vhcrRptView.setOwner(getVoucherOwner(cVchrHdr));
        vhcrRptView.setStatus(getVoucherStatus(cVchrHdr.getStatus()));
        voucherReportList.add(vhcrRptView);
        amt = BigDecimal.ZERO;
    }

    setParamMap();
}

From source file:com.zl.bgec.basicapi.shop.service.impl.ShopServiceImpl.java

@Override
@Transactional(readOnly = true)/*from   w  w  w .  j ava2  s  .co  m*/
public List<Map<String, Object>> getShop(String shopName, String shopTypeNo, String memberNo) throws Exception {
    String sql = "select " + " tsi.shop_no shopNo, " + " tsi.shop_name shopName, " + " tsi.shop_logo shopLogo, "
            + " tsi.shop_summary shopSummary, " + " tsi.is_recommend isRecommend, "
            + " tcc.serviceGrade serviceGrade, " + " tcc.deliveryGrade deliveryGrade, "
            + " if(tcs.shop_no is null,'0','1') isCollect " + " from tbl_shop_info tsi left join   "
            + " (select avg(tcc.service_grade) serviceGrade,avg(tcc.delivery_grade) deliveryGrade , "
            + " tcc.shop_no from tbl_commodity_comment tcc group by(tcc.shop_no) ) tcc on tsi.shop_no = tcc.shop_no "
            + " left join (select * from tbl_shop_collect tcs where tcs.member_no = :memberNo) tcs on tsi.shop_no = tcs.shop_no "
            + "where tsi.status=2 ";
    if (shopTypeNo != null && !shopTypeNo.equals("")) {
        sql = sql + "and tsi.shop_type_no=:shopTypeNo ";
    }
    if (shopName != null && !shopName.equals("")) {
        sql = sql + "and tsi.shop_name like :shopName ";
    }
    Query query = shopDao.createSQLQuery(sql);
    if (shopTypeNo != null && !shopTypeNo.equals("")) {
        query.setParameter("shopTypeNo", shopTypeNo);
    }
    if (shopName != null && !shopName.equals("")) {
        query.setParameter("shopName", "%" + shopName + "%");
    }
    query.setParameter("memberNo", memberNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> results = query.list();
    if (results != null && !results.isEmpty()) {
        for (Map<String, Object> result : results) {
            Double servGrade = result.get("serviceGrade") == null ? 0
                    : Double.valueOf(result.get("serviceGrade").toString());
            BigDecimal serviceGrade = new BigDecimal(servGrade);
            serviceGrade = serviceGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
            result.put("serviceGrade", serviceGrade.doubleValue());
            Double delGrade = result.get("deliveryGrade") == null ? 0
                    : Double.valueOf(result.get("deliveryGrade").toString());
            BigDecimal deliveryGrade = new BigDecimal(delGrade);
            deliveryGrade = deliveryGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
            result.put("deliveryGrade", deliveryGrade.doubleValue());
        }
    }
    return results;
}

From source file:com.panet.imeta.core.row.ValueDataUtil.java

public static Object round(ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB)
        throws KettleValueException {
    if (dataA == null || dataB == null)
        return null;

    switch (metaA.getType()) {
    case ValueMetaInterface.TYPE_NUMBER:
        return new Double(
                Const.round(metaA.getNumber(dataA).doubleValue(), metaB.getInteger(dataB).intValue()));
    case ValueMetaInterface.TYPE_INTEGER:
        return metaA.getInteger(dataA);
    case ValueMetaInterface.TYPE_BIGNUMBER:

        // Round it to the desired number of digits.
        BigDecimal number = metaA.getBigNumber(dataA);
        return number.setScale(metaB.getInteger(dataB).intValue(), BigDecimal.ROUND_HALF_EVEN);

    default://from w  ww  .  j  a  v  a2  s.  co m
        throw new KettleValueException("The 'round' function only works on numeric data");
    }
}

From source file:org.openossad.util.core.row.ValueDataUtil.java

public static Object round(ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB)
        throws OpenDESIGNERValueException {
    if (dataA == null || dataB == null)
        return null;

    switch (metaA.getType()) {
    case ValueMetaInterface.TYPE_NUMBER:
        return new Double(
                Const.round(metaA.getNumber(dataA).doubleValue(), metaB.getInteger(dataB).intValue()));
    case ValueMetaInterface.TYPE_INTEGER:
        return metaA.getInteger(dataA);
    case ValueMetaInterface.TYPE_BIGNUMBER:

        // Round it to the desired number of digits.
        BigDecimal number = metaA.getBigNumber(dataA);
        return number.setScale(metaB.getInteger(dataB).intValue(), BigDecimal.ROUND_HALF_EVEN);

    default:/* w  ww .j a v a2s  .  c  om*/
        throw new OpenDESIGNERValueException("The 'round' function only works on numeric data");
    }
}