Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:org.kuali.kfs.module.bc.document.service.impl.SalarySettingServiceImpl.java

/**
 * @see org.kuali.kfs.module.bc.document.service.SalarySettingService#calculateCSFFteQuantity(java.lang.Integer,
 *      java.lang.Integer, java.math.BigDecimal)
 *///w ww.  j av  a  2 s.com
public BigDecimal calculateCSFFteQuantity(Integer payMonth, Integer normalWorkMonth,
        BigDecimal requestedCSFTimePercent) {
    LOG.debug("calculateCSFFteQuantity() start");

    if (payMonth == null || normalWorkMonth == null || requestedCSFTimePercent == null) {
        return BigDecimal.ZERO;
    }

    BigDecimal payMonthAsDecimal = BigDecimal.valueOf(payMonth);
    BigDecimal normalMonthAsDecimal = BigDecimal.valueOf(normalWorkMonth);
    BigDecimal fundingMonthPercent = normalMonthAsDecimal.divide(payMonthAsDecimal, 5,
            BigDecimal.ROUND_HALF_UP);

    BigDecimal fteQuantity = requestedCSFTimePercent.multiply(fundingMonthPercent)
            .divide(KFSConstants.ONE_HUNDRED.bigDecimalValue());

    return fteQuantity.setScale(5, BigDecimal.ROUND_HALF_UP);
}

From source file:nl.b3p.kaartenbalie.struts.WfsPricingAction.java

public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    request.setAttribute("id", request.getParameter("id"));
    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }//from w  w  w . ja va2  s .  c  om
    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    Date validFrom = FormUtils.FormStringToDate(dynaForm.getString("validFrom"), null);
    Date validUntil = FormUtils.FormStringToDate(dynaForm.getString("validUntil"), null);
    if (validUntil != null && validFrom != null) {
        if (validUntil.before(validFrom)) {
            prepareMethod(dynaForm, request, EDIT, LIST);
            addAlternateMessage(mapping, request, START_END_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
    }
    LayerPricing lp = getLayerPricing(dynaForm, request, true);
    if (lp == null) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, NOTFOUND_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    lp.setValidFrom(validFrom);
    lp.setValidUntil(validUntil);

    WfsLayer layer = null;
    String id = FormUtils.nullIfEmpty(getLayerID(dynaForm));
    if (id != null) {
        layer = getWfsLayerByUniqueName(id);
    }
    if (layer == null || layer.getName() == null || layer.getName().trim().length() == 0) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, LAYER_PLACEHOLDER_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    lp.setServerProviderPrefix(layer.getSpAbbr());
    lp.setLayerName(layer.getName());
    lp.setPlanType(FormUtils.StringToInt(dynaForm.getString("planType")));
    String service = dynaForm.getString("service");
    String operation = null;
    if (service != null && service.equalsIgnoreCase("WMS")) {
        operation = dynaForm.getString("operationWMS");
    } else if (service != null && service.equalsIgnoreCase("WFS")) {
        operation = dynaForm.getString("operationWFS");
    } else {
        service = null;
    }
    if (operation != null && operation.trim().length() == 0) {
        operation = null;
    }
    lp.setService(service);
    lp.setOperation(operation);
    BigDecimal minScale = FormUtils.bdValueNull(dynaForm.getString("minScale"));
    BigDecimal maxScale = FormUtils.bdValueNull(dynaForm.getString("maxScale"));
    String projection = dynaForm.getString("projection");
    if (projection != null && projection.trim().length() == 0) {
        projection = null;
    }
    if (projection != null && (minScale != null || maxScale != null)) {
        boolean scaleOK = false;
        if (minScale != null && minScale.doubleValue() > 0) {
            if (maxScale != null && maxScale.doubleValue() > 0) {
                if (maxScale.compareTo(minScale) > 0) {
                    scaleOK = true;
                }
            }
        }
        if (!scaleOK) {
            prepareMethod(dynaForm, request, LIST, EDIT);
            addAlternateMessage(mapping, request, SCALE_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
        if (minScale != null) {
            lp.setMinScale(minScale.setScale(2, RoundingMode.HALF_UP));
        }
        if (maxScale != null) {
            lp.setMaxScale(maxScale.setScale(2, RoundingMode.HALF_UP));
        }
        lp.setProjection(projection);
    }
    BigDecimal unitPrice = FormUtils.bdValueNull(dynaForm.getString("unitPrice"));
    /* 
     * || door && vervangen. Price is namelijk verplicht en dus nooit null
     * en hij kwam dus altijd door de check. Ook als het bedrag 0 was.
     */
    if (unitPrice != null && unitPrice.doubleValue() > 0.0) {
        lp.setUnitPrice(unitPrice.setScale(2, RoundingMode.HALF_UP));
    } else {
        lp.setLayerIsFree(Boolean.TRUE);
    }
    em.persist(lp);
    return super.save(mapping, dynaForm, request, response);
}

From source file:org.meerkat.services.WebApp.java

/**
 * getLatencyAverage/*from  w  w w . ja v  a2s.  co m*/
 * 
 * @return Latency average
 */
private final double getAvailabilityAverage() {
    double availAvg = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(
                "SELECT AVG(AVAILABILITY) FROM MEERKAT.EVENTS WHERE APPNAME LIKE '" + this.name + "'");
        rs = ps.executeQuery();

        rs.next();
        availAvg = rs.getDouble(1);

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd = new BigDecimal(availAvg);
    bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
    availAvg = bd.doubleValue();

    return availAvg;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getAppLoadTimeAVG//from   w  ww.j  a v a2  s  . c o  m
 * @return
 */
public double getAppLoadTimeAVG() {
    int decimalPlaces = 2;
    double loadTimeAVG = 0.0;
    PreparedStatement ps;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(
                "SELECT AVG(LOADTIME) FROM MEERKAT.EVENTS WHERE APPNAME LIKE '" + this.name + "'");
        rs = ps.executeQuery();

        rs.next();
        loadTimeAVG = rs.getInt(1);

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query number of events from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd = new BigDecimal(loadTimeAVG);
    bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_DOWN);
    loadTimeAVG = bd.doubleValue();

    return loadTimeAVG;
}

From source file:nl.b3p.kaartenbalie.struts.WmsPricingAction.java

public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    request.setAttribute("id", request.getParameter("id"));
    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }//w  w w.j  a v a 2 s.c  om
    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    Date validFrom = FormUtils.FormStringToDate(dynaForm.getString("validFrom"), null);
    Date validUntil = FormUtils.FormStringToDate(dynaForm.getString("validUntil"), null);
    if (validUntil != null && validFrom != null) {
        if (validUntil.before(validFrom)) {
            prepareMethod(dynaForm, request, EDIT, LIST);
            addAlternateMessage(mapping, request, START_END_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
    }
    LayerPricing lp = getLayerPricing(dynaForm, request, true);
    if (lp == null) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, NOTFOUND_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    lp.setValidFrom(validFrom);
    lp.setValidUntil(validUntil);

    Layer layer = null;
    String id = FormUtils.nullIfEmpty(getLayerID(dynaForm));
    if (id != null) {
        layer = getLayerByUniqueName(id);
    }
    if (layer == null || layer.getName() == null || layer.getName().trim().length() == 0) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, LAYER_PLACEHOLDER_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    lp.setServerProviderPrefix(layer.getSpAbbr());
    lp.setLayerName(layer.getName());
    lp.setPlanType(FormUtils.StringToInt(dynaForm.getString("planType")));
    String service = dynaForm.getString("service");
    String operation = null;
    if (service != null && service.equalsIgnoreCase("WMS")) {
        operation = dynaForm.getString("operationWMS");
    } else if (service != null && service.equalsIgnoreCase("WFS")) {
        operation = dynaForm.getString("operationWFS");
    } else {
        service = null;
    }
    if (operation != null && operation.trim().length() == 0) {
        operation = null;
    }
    lp.setService(service);
    lp.setOperation(operation);
    BigDecimal minScale = FormUtils.bdValueNull(dynaForm.getString("minScale"));
    BigDecimal maxScale = FormUtils.bdValueNull(dynaForm.getString("maxScale"));
    String projection = dynaForm.getString("projection");
    if (projection != null && projection.trim().length() == 0) {
        projection = null;
    }
    if (projection != null && (minScale != null || maxScale != null)) {
        boolean scaleOK = false;
        if (minScale != null && minScale.doubleValue() > 0) {
            if (maxScale != null && maxScale.doubleValue() > 0) {
                if (maxScale.compareTo(minScale) > 0) {
                    scaleOK = true;
                }
            }
        }
        if (!scaleOK) {
            prepareMethod(dynaForm, request, LIST, EDIT);
            addAlternateMessage(mapping, request, SCALE_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
        if (minScale != null) {
            lp.setMinScale(minScale.setScale(2, RoundingMode.HALF_UP));
        }
        if (maxScale != null) {
            lp.setMaxScale(maxScale.setScale(2, RoundingMode.HALF_UP));
        }
        lp.setProjection(projection);
    }
    BigDecimal unitPrice = FormUtils.bdValueNull(dynaForm.getString("unitPrice"));
    /* 
     * || door && vervangen. Price is namelijk verplicht en dus nooit null
     * en hij kwam dus altijd door de check. Ook als het bedrag 0 was.
     */
    if (unitPrice != null && unitPrice.doubleValue() > 0.0) {
        lp.setUnitPrice(unitPrice.setScale(2, RoundingMode.HALF_UP));
    } else {
        lp.setLayerIsFree(Boolean.TRUE);
    }
    em.persist(lp);
    prepareMethod(dynaForm, request, LIST, EDIT);
    addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES);
    return getDefaultForward(mapping, request);
}

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);
            }//w  w  w.j  a v  a  2s . 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.meerkat.services.WebApp.java

/**
 * getAvailabilityIndicator//from   w  w w. j a  v  a  2  s .  com
 * @return    1 if last availability higher than availability average
 *          -1 if last avail. lower than avail. average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getAvailabilityIndicator() {
    double doubleAvailAverage = getAvailabilityAverage();
    BigDecimal bd = new BigDecimal(doubleAvailAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double availAverage = bd.doubleValue();

    // get the value of last event
    double lastAvailability = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxId = embDB.getMaxIDofApp(this.getName());
    try {
        ps = conn.prepareStatement("SELECT ID, AVAILABILITY " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.getName() + "' " + "AND ID = " + maxId);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastAvailability = rs.getDouble(2);
        }

        rs.close();
        ps.close();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastAvailability);
    bd1 = bd1.setScale(2, BigDecimal.ROUND_DOWN);
    lastAvailability = bd1.doubleValue();

    if (lastAvailability > availAverage) {
        return 1;
    } else if (lastAvailability < availAverage) {
        return -1;
    }

    return 0;
}

From source file:org.meerkat.services.WebApp.java

/**
 * /*  w  w  w . java  2 s  . com*/
 * getLatencyIndicator
 * @return    1 if last latency higher than latency average
 *          -1 if last latency lower than latency average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getLatencyIndicator() {
    double doubleLatencyAverage = getLatencyAverage();
    BigDecimal bd = new BigDecimal(doubleLatencyAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double latencyAverage = bd.doubleValue();

    // get the value of last event
    double lastLatency = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxID = embDB.getMaxIDofApp(this.name);

    try {
        ps = conn.prepareStatement("SELECT ID, LATENCY " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.name + "' " + "AND ID = " + maxID);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastLatency = rs.getDouble(2);
        }

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastLatency);
    bd1 = bd1.setScale(2, BigDecimal.ROUND_DOWN);
    lastLatency = bd1.doubleValue();

    if (lastLatency > latencyAverage) {
        return 1;
    } else if (lastLatency < latencyAverage) {
        return -1;
    }

    return 0;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getLoadTimeIndicator/*from w  ww.  j  a  va2  s .  c om*/
 * @return    1 if last load time higher than load time average
 *          -1 if last load time lower than load time average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getLoadTimeIndicator() {
    double doubleLoadTimeAverage = getAppLoadTimeAVG();
    BigDecimal bd = new BigDecimal(doubleLoadTimeAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double loadTimeAverage = bd.doubleValue();

    // get the value of last event
    double lastLoadTime = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxID = embDB.getMaxIDofApp(this.name);

    try {
        ps = conn.prepareStatement("SELECT ID, LOADTIME " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.name + "' " + "AND ID = " + maxID);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastLoadTime = rs.getDouble(2);
        }

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average load time from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastLoadTime);
    bd1 = bd1.setScale(3, BigDecimal.ROUND_DOWN);
    lastLoadTime = bd1.doubleValue();

    if (lastLoadTime > loadTimeAverage) {
        return 1;
    } else if (lastLoadTime < loadTimeAverage) {
        return -1;
    }

    return 0;
}