Example usage for java.math RoundingMode HALF_EVEN

List of usage examples for java.math RoundingMode HALF_EVEN

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_EVEN.

Prototype

RoundingMode HALF_EVEN

To view the source code for java.math RoundingMode 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:de.brendamour.jpasskit.server.PKRestletServerResourceFactory.java

public PKPassResource getPKPassResource() {
    return new PKPassResource("passes/coupons.raw") {

        @Override/*from w  ww  .  ja  v a 2 s .  c  o  m*/
        protected GetPKPassResponse handleGetLatestVersionOfPass(final String passTypeIdentifier,
                final String serialNumber, final String authString, final Date modifiedSince)
                throws PKAuthTokenNotValidException, PKPassNotModifiedException {
            PKPass pass = new PKPass();
            try {
                pass = jsonObjectMapper.readValue(new File("passes/coupons.raw/pass2.json"), PKPass.class);

                float newAmount = getNewRandomAmount();
                PKStoreCard storeCard = pass.getStoreCard();
                List<PKField> primaryFields = storeCard.getPrimaryFields();
                for (PKField field : primaryFields) {
                    if ("balance".equals(field.getKey())) {
                        field.setValue(newAmount);
                        field.setChangeMessage("Amount changed to %@");
                        break;
                    }

                }
                List<PKField> headerFields = storeCard.getHeaderFields();
                for (PKField field : headerFields) {
                    if ("balanceHeader".equals(field.getKey())) {
                        field.setValue(newAmount);
                        break;
                    }

                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            GetPKPassResponse getPKPassResponse = new GetPKPassResponse(pass, new Date());

            return getPKPassResponse;
        }

        private float getNewRandomAmount() {
            Random random = new Random();
            float amount = random.nextInt(100) + random.nextFloat();
            BigDecimal bigDecimalForRounding = new BigDecimal(amount).setScale(2, RoundingMode.HALF_EVEN);
            return bigDecimalForRounding.floatValue();
        }

        @Override
        protected PKSigningInformation getSingingInformation() {
            try {
                return PKSigningUtil.loadSigningInformationFromPKCS12FileAndIntermediateCertificateFile(
                        PKCS12_FILE_PATH, PKCS12_FILE_PASSWORD, APPLE_WWDRCA_CERT_PATH);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    };
}

From source file:easycare.load.util.db.loader.UserDataLoader.java

private void createUsersWithSubsetLocations(ContextOfCurrentLoad context, Organisation organisation,
        String organisationNumber) {
    List<Location> locations = organisation.activeLocations();
    BigDecimal totalLocations = BigDecimal.valueOf(locations.size());
    BigDecimal twoThirdLocations = totalLocations
            .divide(BigDecimal.valueOf(_THREE), _SIX, RoundingMode.HALF_EVEN).multiply(BigDecimal.valueOf(2))
            .setScale(0, RoundingMode.CEILING);
    Location[] locationsToAdd = locations.subList(0, twoThirdLocations.intValue()).toArray(new Location[0]);
    List<Role> roles = newArrayList(seedData.getRole(ROLE_CLINICIAN));
    buildUser(context, "remy" + organisationNumber, "Remy", "Roam", organisation, roles, organisationNumber,
            locationsToAdd);//w w  w . j  ava 2  s .c o  m
}

From source file:com.artivisi.biller.simulator.service.impl.PlnSimulatorServiceImpl.java

private void generateTagihanNormal(Integer current, int i) {
    Pelanggan p = new Pelanggan();
    p.setNama("Pelang'gan Dumm\"y " + current);

    TagihanPascabayar t = new TagihanPascabayar();
    t.setPelanggan(p);/*from   w w  w.  java 2s  .com*/
    t.setBillPeriod(new Date());
    t.setDueDate(new DateTime().dayOfMonth().setCopy(20).toDate());
    t.setMeterReadDate(new DateTime().minusDays(10).toDate());
    t.setBill(new BigDecimal(Math.random() * 100000).setScale(2, RoundingMode.HALF_EVEN));
    t.setVat(t.getBill().divide(new BigDecimal(10)));

    Integer prev = Double.valueOf(Math.random() * 100).intValue();
    Integer curr = prev + Double.valueOf(Math.random() * 10).intValue();

    t.setPreviousMeterRead1(String.valueOf(prev));
    t.setPreviousMeterRead2(String.valueOf(prev));
    t.setPreviousMeterRead3(String.valueOf(prev));
    t.setCurrentMeterRead1(String.valueOf(curr));
    t.setCurrentMeterRead2(String.valueOf(curr));
    t.setCurrentMeterRead3(String.valueOf(curr));

    if (i % 4 == 0) {
        p.setIdpel("51" + org.apache.commons.lang.StringUtils.leftPad(current.toString(), 10, "0"));
        p.setMeterNumber("51" + org.apache.commons.lang.StringUtils.leftPad(current.toString(), 9, "0"));
        p.setServiceUnit("51");
        p.setServiceUnitPhone("51-1234567890");
        p.setPowerConsumingCategory("900");
        p.setSubscriberSegmentation("R1");
        t.setInsentif(t.getBill().multiply(new BigDecimal(0.8)));
    } else if (i % 3 == 0) {
        p.setIdpel("52" + org.apache.commons.lang.StringUtils.leftPad(current.toString(), 10, "0"));
        p.setMeterNumber("52" + org.apache.commons.lang.StringUtils.leftPad(current.toString(), 9, "0"));
        p.setServiceUnit("52");
        p.setServiceUnitPhone("52-1234567890");
        p.setPowerConsumingCategory("1300");
        p.setSubscriberSegmentation("R2");
        t.setInsentif(t.getBill().multiply(new BigDecimal(-0.8)));
    } else if (i % 2 == 0) {
        p.setIdpel("53" + org.apache.commons.lang.StringUtils.leftPad(current.toString(), 10, "0"));
        p.setMeterNumber("53" + org.apache.commons.lang.StringUtils.leftPad(current.toString(), 9, "0"));
        p.setServiceUnit("53");
        p.setServiceUnitPhone("53-1234567890");
        p.setPowerConsumingCategory("2000");
        p.setSubscriberSegmentation("S1");
    } else {
        p.setIdpel("54" + org.apache.commons.lang.StringUtils.leftPad(current.toString(), 10, "0"));
        p.setMeterNumber("54" + org.apache.commons.lang.StringUtils.leftPad(current.toString(), 9, "0"));
        p.setServiceUnit("54");
        p.setServiceUnitPhone("54-1234567890");
        p.setPowerConsumingCategory("2500");
        p.setSubscriberSegmentation("S2");
    }

    sessionFactory.getCurrentSession().saveOrUpdate(p);
    sessionFactory.getCurrentSession().saveOrUpdate(t);
}

From source file:fr.hoteia.qalingo.core.web.util.impl.RequestUtilImpl.java

/**
 *
 *//*from   www .  ja v a 2s.  co m*/
public NumberFormat getCartItemPriceNumberFormat(final RequestData requestData, final String currencyCode)
        throws Exception {
    return getNumberFormat(requestData, currencyCode, RoundingMode.HALF_EVEN, 2, 2, 1000000, 1);
}

From source file:org.openvpms.web.echo.style.StylePropertyEvaluator.java

/**
 * Rounds a numeric value to a long./*from   ww w. j a  va2s  .c om*/
 *
 * @param value the value to round
 * @return the rounded value
 */
private long round(Number value) {
    if (value instanceof Integer || value instanceof Long) {
        return value.longValue();
    }
    BigDecimal result = (value instanceof BigDecimal) ? (BigDecimal) value
            : new BigDecimal(value.doubleValue());
    return result.setScale(0, RoundingMode.HALF_EVEN).longValue();
}

From source file:com.benfante.minimark.blo.ResultCalculationBo.java

private void evaluateClosedQuestion(ClosedQuestionFilling closedQuestionFilling, String evaluationType,
        BigDecimal minimumEvaluation) {
    BigDecimal result = new BigDecimal("0.00");
    if (evaluationType == null
            || Assessment.EVALUATION_CLOSED_SUM_CORRECT_MINUS_WRONG_ANSWERS.equals(evaluationType)) {
        final BigDecimal weightCorrect = closedQuestionFilling.weightCorrectAnswers();
        final BigDecimal weightSelectedCorrect = closedQuestionFilling.weightSelectedCorrectAnswers();
        final BigDecimal weightWrong = closedQuestionFilling.weightWrongAnswers();
        final BigDecimal weightSelectedWrong = closedQuestionFilling.weightSelectedWrongAnswers();
        BigDecimal normalizedCorrect = new BigDecimal("1.00");
        if (!BigDecimal.ZERO.equals(weightCorrect)) {
            // nc = #selectedCorrect/#correct
            normalizedCorrect = weightSelectedCorrect.divide(weightCorrect, 2, RoundingMode.HALF_EVEN);
        }//  w w  w. jav a 2 s.  c  o  m
        BigDecimal normalizedWrong = new BigDecimal("1.00");
        if (!BigDecimal.ZERO.equals(weightWrong)) {
            // nw = #selectedWrong/#wrong
            normalizedWrong = weightSelectedWrong.divide(weightWrong, 2, RoundingMode.HALF_EVEN);
        }
        // r = nc-nw
        result = normalizedCorrect.subtract(normalizedWrong);
    } else if (Assessment.EVALUATION_CLOSED_SUM_CORRECT_ANSWERS.equals(evaluationType)) {
        final BigDecimal weightCorrect = closedQuestionFilling.weightCorrectAnswers();
        final BigDecimal weightSelectedCorrect = closedQuestionFilling.weightSelectedCorrectAnswers();
        result = new BigDecimal("1.00");
        if (!BigDecimal.ZERO.equals(weightCorrect)) {
            // r = #selectedCorrect/#correct
            result = weightSelectedCorrect.divide(weightCorrect, 2, RoundingMode.HALF_EVEN);
        }
    }
    // r = max(r, minimumEvaluation)
    if (minimumEvaluation != null) {
        result = result.max(minimumEvaluation);
    }
    closedQuestionFilling.setMark(result);
}

From source file:universal.Calc.java

private BigDecimal DOT(BigDecimal[] first, BigDecimal[] sec) {
    BigDecimal sum = BigDecimal.ZERO;
    for (int n = 0; n < 6; ++n) {
        sum = sum.add(first[n].multiply(sec[n]).setScale(100, RoundingMode.HALF_EVEN));
    }//from   w  w  w  . j  a v a2 s  .c o m
    return sum;
}

From source file:com.mobileman.kuravis.core.services.event.impl.EventServiceImpl.java

/**
 * {@inheritDoc}//from w ww .j  a v a2 s  . c  om
 * 
 * @see com.mobileman.kuravis.core.services.event.EventService#createReviewEvent(com.mongodb.DBObject)
 */
@Override
public void createReviewEvent(DBObject treatmentReview) {
    if (treatmentReview.get(TreatmentReview.ID) == null) {
        throw ErrorUtils.exception("Review ID is null", ErrorCodes.INCORRECT_PARAMETER);
    }
    if (treatmentReview.get(TreatmentReview.DISEASE) == null) {
        throw ErrorUtils.exception("Review disease is null", ErrorCodes.INCORRECT_PARAMETER);
    }
    if (treatmentReview.get(TreatmentReview.TREATMENT) == null) {
        throw ErrorUtils.exception("Review treatment is null", ErrorCodes.INCORRECT_PARAMETER);
    }

    DBObject disease = (DBObject) treatmentReview.get(TreatmentReview.DISEASE);
    DBObject treatment = (DBObject) treatmentReview.get(TreatmentReview.TREATMENT);

    Date createdOn = (Date) treatmentReview.get(CREATED_ON);
    if (createdOn == null) {
        createdOn = new Date();
    }

    ReviewEvent reviewEvent = new ReviewEvent();
    reviewEvent.setStart(createdOn);
    reviewEvent.setEnd(createdOn);
    reviewEvent.setReviewId(getEntityId(treatmentReview));
    reviewEvent.setDisease(new Disease(EntityUtils.getEntityId(disease), EntityUtils.getEntityName(disease)));
    reviewEvent.setTreatment(
            new Treatment(EntityUtils.getEntityId(treatment), EntityUtils.getEntityName(treatment)));

    if (treatmentReview.get(TreatmentReview.RATING) != null) {
        reviewEvent
                .setRating(new BigDecimal(((Number) treatmentReview.get(TreatmentReview.RATING)).doubleValue())
                        .setScale(4, RoundingMode.HALF_EVEN));
    }

    create(reviewEvent);
}

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.EditFragment.java

/**
 * Overriden method from Fragment. Sets the appropriate TextView and ImageView
 * if the user is returning from changing the location or image. If the user is
 * returning from changing the location, the new coordinates are placed on the
 * edit_location_button Button.//from   w  w  w.j  a  v  a2  s. co  m
 */
@Override
public void onResume() {
    super.onResume();
    Bundle args = getArguments();
    if (EditFragment.oldText != null) {
        TextView oldTextView = (TextView) getActivity().findViewById(R.id.old_comment_text);
        oldTextView.setText(EditFragment.oldText);
    }
    if (args != null) {
        if (args.containsKey("LATITUDE") && args.containsKey("LONGITUDE")) {
            Button locButton = (Button) getActivity().findViewById(R.id.edit_location_button);
            if (args.getString("LocationType") == "CURRENT_LOCATION") {
                locButton.setText("Current Location");
            } else {
                GeoLocation geoLocation = editComment.getLocation();
                Double lat = args.getDouble("LATITUDE");
                Double lon = args.getDouble("LONGITUDE");
                geoLocation.setCoordinates(lat, lon);

                String locationDescription = args.getString("locationDescription");
                geoLocation.setLocationDescription(locationDescription);

                DecimalFormat format = new DecimalFormat();
                format.setRoundingMode(RoundingMode.HALF_EVEN);
                format.setMinimumFractionDigits(0);
                format.setMaximumFractionDigits(4);

                locButton.setText("Location: Set");
            }
        }
    }
}

From source file:org.openmrs.module.billing.web.controller.billingqueuedia.DueBillCollect.java

@RequestMapping(value = "/module/billing/dueCollect.htm", method = RequestMethod.POST)
public String dueCollect(@RequestParam("patientId") Integer patientId,
        @RequestParam(value = "refDocId", required = false) Integer refDocId,
        @RequestParam(value = "rmpId", required = false) Integer rmpId, @RequestParam("billId") Integer billId,
        @RequestParam("indCount") Integer indCount,
        @RequestParam(value = "per", required = false) String discount,
        @RequestParam(value = "encounterId", required = false) String encounterId, HttpServletRequest request,
        Model model) throws ParseException {

    Patient patient = Context.getPatientService().getPatient(patientId);

    MedisunService ms = Context.getService(MedisunService.class);
    org.openmrs.module.hospitalcore.BillingService billingService = Context
            .getService(org.openmrs.module.hospitalcore.BillingService.class);

    User user = Context.getAuthenticatedUser();

    BillableService service;/* w  w w  . ja v a  2  s. c  om*/

    BigDecimal totalBill = NumberUtils.createBigDecimal(request.getParameter("totalBill"));
    BigDecimal payableAmount = NumberUtils.createBigDecimal(request.getParameter("payableamount"));
    BigDecimal paidAmount = NumberUtils.createBigDecimal(request.getParameter("paidamount"));
    BigDecimal dueAmount = NumberUtils.createBigDecimal(request.getParameter("dueamount"));
    BigDecimal discountAmount = NumberUtils.createBigDecimal(request.getParameter("disAmounut"));
    BigDecimal secLess = NumberUtils.createBigDecimal(request.getParameter("secLess"));

    BigDecimal totDis = (discountAmount.add(secLess));

    String due = null;
    if (dueAmount.signum() < 1) {
        due = "PAID";
    } else {
        due = "DUE";
    }

    DiaPatientServiceBill dpsb = ms.getDiaPatientServiceBillId(billId);
    dpsb.setDueAmount(dueAmount);
    dpsb.setBillingStatus(due);
    dpsb.setDiscountAmount(totDis);
    ms.reSaveDia(dpsb);

    model.addAttribute("billId", dpsb.getBillId());
    model.addAttribute("paid", paidAmount);

    model.addAttribute("refDocId", refDocId);

    DiaPatientServiceBillCollect dBillColl = new DiaPatientServiceBillCollect();
    dBillColl.setPatientId(patientId);
    dBillColl.setDiaPatientServiceBill(dpsb);
    dBillColl.setUser(user);
    dBillColl.setCreatedDate(new Date());
    dBillColl.setActualAmount(totalBill);
    dBillColl.setPaidAmount(paidAmount);
    dBillColl.setPayableAmount(payableAmount);
    dBillColl.setDueAmount(dueAmount);
    dBillColl.setDiscountAmount(secLess);
    dBillColl.setDuePaidStatus(true);
    // dBillColl.setDuePaid(duePaid);
    ms.saveDiaPatientServiceBillCollect(dBillColl);

    model.addAttribute("dBillCollect", dBillColl);

    BigDecimal totCom = BigDecimal.ZERO;
    BigDecimal servicePrice = BigDecimal.ZERO;
    String sername = null;

    /// Due collect amount, get commission calculation save in Dia Commission Cal
    for (Integer i = 1; i <= indCount; i++) {

        //    String servicename = request.getParameter("service");
        BigDecimal unitPrice = NumberUtils.createBigDecimal(request.getParameter(i.toString() + "unitprice")); // Quantity * unitPrice

        String servicename = request.getParameter(i.toString() + "service");
        service = billingService.getServiceByConceptName(servicename);

        if (((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678")))) {
            sername = servicename + "," + sername; // for commison
            servicePrice = servicePrice.add(unitPrice);
        }

        // BigDecimal ind = NumberUtils.createBigDecimal(indCount.toString());
        //BigDecimal da = discountAmount.divide(ind, 2, RoundingMode.CEILING);
        if (dpsb.getBillingStatus() == "PAID") {

            BigDecimal oneHundred = new BigDecimal(100);
            BigDecimal le = null;
            System.out.println("*******" + service.getCategory().getId());
            if ((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678"))) {
                if (!StringUtils.isBlank(discount)) {
                    BigDecimal dis;
                    dis = new BigDecimal(discount);
                    BigDecimal less = (unitPrice.multiply(dis)).divide(oneHundred, 0, RoundingMode.HALF_EVEN);
                    le = less;
                } else {
                    le = new BigDecimal(0);
                }
            }

            //if (!StringUtils.equalsIgnoreCase(service.getCommission(), "0")) {
            if ((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678"))) {
                BigDecimal percentage = NumberUtils.createBigDecimal(service.getCommission());
                BigDecimal com = (unitPrice.multiply(percentage)).divide(oneHundred);
                totCom = totCom.add(com);

                servicePrice = servicePrice.add(unitPrice);
            }
            if ((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678"))) {

                DiaCommissionCal diaComCal = new DiaCommissionCal();
                diaComCal.setDiaPatientServiceBill(dpsb);
                diaComCal.setPatient(patient);
                diaComCal.setServiceName(service.getName());
                diaComCal.setServiceId(service.getServiceId());
                diaComCal.setServicePrice(unitPrice);
                //diaComCal.setLessAmount(discountAmount);
                diaComCal.setLessAmount(le);
                diaComCal.setCommission(service.getCommission());
                diaComCal.setCreatedDate(new Date());
                diaComCal.setCreator(user.getId());
                diaComCal.setRefId(refDocId); ////
                diaComCal.setRefRmpId(rmpId);
                ms.saveDiaComCal(diaComCal);
            }
        }

    }

    /// For diacommissionall
    if (sername != null && dpsb.getBillingStatus() == "PAID") {
        sername = sername.replace(",null", "");

        DiaCommissionCalAll diaAll = new DiaCommissionCalAll();
        diaAll.setDiaPatientServiceBill(dpsb);
        diaAll.setPatient(patient);
        diaAll.setServiceName(sername);
        diaAll.setServicePrice(servicePrice);
        diaAll.setLessAmount(discountAmount);
        diaAll.setComAmount(totCom);
        diaAll.setCreatedDate(new Date());
        diaAll.setCreator(Context.getAuthenticatedUser().getId());
        diaAll.setRefId(refDocId);
        diaAll.setRefRmp(rmpId);
        ms.saveDiaComAll(diaAll);
    }

    return "redirect:/module/billing/dueprint.htm?patientId=" + patientId;
    //module/billing/directbillingqueue.form

}