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:com.salesmanager.core.util.CurrencyUtil.java

/**
 * Get the measure according to the appropriate measure base. If the measure
 * configured in store is LB and it needs KG then the appropriate
 * calculation is done//from  ww  w  .j  a v  a  2s  . c  o  m
 * 
 * @param weight
 * @param store
 * @param base
 * @return
 */
public static double getWeight(double weight, MerchantStore store, String base) {

    double weightConstant = 2.2;
    if (base.equals(Constants.LB_WEIGHT_UNIT)) {
        if (store.getWeightunitcode().equals(Constants.LB_WEIGHT_UNIT)) {
            return new BigDecimal(String.valueOf(weight)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        } else {// pound = kilogram
            double answer = weight * weightConstant;
            BigDecimal w = new BigDecimal(answer);
            return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
    } else {// need KG
        if (store.getWeightunitcode().equals(Constants.KG_WEIGHT_UNIT)) {
            return new BigDecimal(String.valueOf(weight)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        } else {

            double answer = weight / weightConstant;
            BigDecimal w = new BigDecimal(answer);
            return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        }
    }
}

From source file:com.base.dao.sql.ReflectionUtils.java

private static double processDecimal(Object value) {
    String objs = String.valueOf(value);
    double dbvalue = Double.valueOf(objs);
    BigDecimal bg = new BigDecimal(dbvalue);
    double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    return f1;//www  . j ava 2  s.c o  m
}

From source file:org.kalypso.gml.ui.internal.coverage.CoverageColorRangeAction.java

/**
 * protect against too many digits; still ugly, as number of digits depends on real data type...
 *///from   w w w .  ja  v  a  2  s. com
private BigDecimal asBigDecimal(final Double value) {
    final BigDecimal decimal = new BigDecimal(Double.toString(value));
    if (decimal.scale() < 5)
        return decimal;

    return decimal.setScale(4, BigDecimal.ROUND_HALF_UP);
}

From source file:org.codhaus.groovy.grails.validation.ScaleConstraint.java

/**
 * @return the <code>BigDecimal</code> object that results from applying the contraint's scale to the underlying number
 * @param originalValue The original value
 *//*  ww  w .j  av a 2s . c  o m*/
private BigDecimal getScaledValue(BigDecimal originalValue) {
    return originalValue.setScale(scale, BigDecimal.ROUND_HALF_UP);
}

From source file:uk.co.onehp.trickle.services.betfair.BetfairServiceImpl.java

@Override
@Transactional//from   ww w  . j  a v  a  2  s  .c om
public void placeBet(Bet bet) {
    PlaceBetsReq placeBetsReq = new PlaceBetsReq();
    placeBetsReq.setBets(new ArrayOfPlaceBets());
    //if price falls within range
    //if chasing
    //place entire amount at chased price, market on close
    //else
    //place as much as possible at highest price, market on close
    //place remainder at SP limit on close
    //else
    //place at SP limit on close
    Strategy strategy = bet.getStrategy();
    BigDecimal liability = strategy.getLiability().divide(new BigDecimal(bet.getNumberOfSplits()),
            BigDecimal.ROUND_HALF_UP);
    Pricing bestPricing = BettingUtil.bestPrice(bet.getHorse().getPrices(), strategy.getAspect());
    if (bestPricing.getPrice().compareTo(strategy.getMaxOdds()) <= 0
            && bestPricing.getPrice().compareTo(strategy.getMinOdds()) >= 0) {
        if (strategy.getChasePriceByTick() == 0) {
            if (bestPricing.getAmountAvailable().compareTo(liability) >= 0) {
                placeBetsReq.getBets().getPlaceBets()
                        .add(createMOCExchangeBet(bet, liability, bestPricing.getPrice()));
            } else {
                placeBetsReq.getBets().getPlaceBets().add(
                        createMOCExchangeBet(bet, bestPricing.getAmountAvailable(), bestPricing.getPrice()));
                placeBetsReq.getBets().getPlaceBets()
                        .add(createLimitedSPBet(bet, liability.subtract(bestPricing.getAmountAvailable())));
            }
        } else {
            placeBetsReq.getBets().getPlaceBets()
                    .add(createMOCExchangeBet(bet, liability, BettingUtil.findChasePrice(bestPricing.getPrice(),
                            strategy.getChasePriceByTick(), strategy.getAspect())));
        }
    } else {
        placeBetsReq.getBets().getPlaceBets().add(createLimitedSPBet(bet, liability));
    }
    sendRequest(placeBetsReq);
}

From source file:nu.mine.kino.projects.utils.Utils.java

public static double round(double d, int scale) {
    // if (!Double.isNaN(d)) {
    // d = Math.round(d * 1000.0) / 1000.0;
    // }//w w  w.j  av a 2 s .c o  m
    // return d;
    if (Double.isNaN(d)) {
        return d;
    }
    // return d;
    return new BigDecimal(d).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}

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

@Override
public JsonElement serialize(final DataTable<PropertyMVInfo> baseRegisterResponse, final Type type,
        final JsonSerializationContext jsc) {
    final List<PropertyMVInfo> baseRegisterResult = baseRegisterResponse.getData();
    final JsonArray baseRegisterResultData = new JsonArray();
    baseRegisterResult.forEach(baseRegisterResultObj -> {
        final JsonObject jsonObject = new JsonObject();

        final BigDecimal taxRate = propertyTaxUtil.getTaxRates();
        final Map<String, BigDecimal> valuesMap = getTaxDetails(baseRegisterResultObj);

        final BigDecimal marketValue = baseRegisterResultObj.getMarketValue() == null ? BigDecimal.ZERO
                : baseRegisterResultObj.getMarketValue();
        final BigDecimal capitalValue = baseRegisterResultObj.getCapitalValue() == null ? BigDecimal.ZERO
                : baseRegisterResultObj.getCapitalValue();

        final BigDecimal higherValueForImposedTax = marketValue.compareTo(capitalValue) > 0
                ? marketValue.setScale(2, BigDecimal.ROUND_HALF_UP)
                : capitalValue.setScale(2, BigDecimal.ROUND_HALF_UP);

        BigDecimal currPenaltyFine = BigDecimal.ZERO;
        if (baseRegisterResultObj.getAggrCurrFirstHalfPenaly() != null)
            currPenaltyFine = currPenaltyFine.add(baseRegisterResultObj.getAggrCurrFirstHalfPenaly());
        if (baseRegisterResultObj.getAggrCurrSecondHalfPenaly() != null)
            currPenaltyFine = currPenaltyFine.add(baseRegisterResultObj.getAggrCurrSecondHalfPenaly());

        final BigDecimal currentColl = baseRegisterResultObj.getAggrCurrFirstHalfColl() == null
                ? BigDecimal.ZERO
                        .add(baseRegisterResultObj.getAggrCurrSecondHalfColl() == null ? BigDecimal.ZERO
                                : baseRegisterResultObj.getAggrCurrSecondHalfColl())
                : baseRegisterResultObj.getAggrCurrFirstHalfColl();

        final BigDecimal arrColl = baseRegisterResultObj.getAggrArrColl() != null
                ? baseRegisterResultObj.getAggrArrColl()
                : BigDecimal.ZERO;
        final BigDecimal totalColl = arrColl.add(currentColl);
        final BigDecimal currTotal = baseRegisterResultObj.getAggrCurrFirstHalfDmd() == null
                ? BigDecimal.ZERO.add(baseRegisterResultObj.getAggrCurrSecondHalfDmd() == null ? BigDecimal.ZERO
                        : baseRegisterResultObj.getAggrCurrSecondHalfDmd())
                : baseRegisterResultObj.getAggrCurrFirstHalfDmd();
        jsonObject.addProperty("assessmentNo", baseRegisterResultObj.getPropertyId());
        jsonObject.addProperty("oldAssessmentNo",
                StringUtils.isNotBlank(baseRegisterResultObj.getOldMuncipalNum())
                        ? baseRegisterResultObj.getOldMuncipalNum()
                        : "NA");
        jsonObject.addProperty("sitalArea",
                baseRegisterResultObj.getSitalArea().setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.addProperty("ward", baseRegisterResultObj.getWard().getBoundaryNum());
        jsonObject.addProperty("ownerName", baseRegisterResultObj.getOwnerName());
        jsonObject.addProperty("surveyNo",
                StringUtils.isNotBlank(baseRegisterResultObj.getSurveyNo())
                        ? baseRegisterResultObj.getSurveyNo()
                        : "NA");
        jsonObject.addProperty("taxationRate", taxRate);
        jsonObject.addProperty("marketValue", marketValue.toString());
        jsonObject.addProperty("documentValue", capitalValue.toString());
        jsonObject.addProperty("higherValueForImposedtax", higherValueForImposedTax.toString());
        jsonObject.addProperty("isExempted", baseRegisterResultObj.getIsExempted() ? "Yes" : "No");
        jsonObject.addProperty("propertyTaxFirstHlf",
                baseRegisterResultObj.getAggrCurrFirstHalfDmd() == null ? BigDecimal.ZERO
                        : baseRegisterResultObj.getAggrCurrFirstHalfDmd());

        if (!valuesMap.isEmpty()) {
            jsonObject.addProperty("libraryCessTaxFirstHlf",
                    valuesMap.get(CURR_FIRST_HALF_LIB_CESS) == null ? BigDecimal.ZERO
                            : valuesMap.get(CURR_FIRST_HALF_LIB_CESS));
            jsonObject.addProperty("libraryCessTaxSecondHlf",
                    valuesMap.get(CURR_SECOND_HALF_LIB_CESS) == null ? BigDecimal.ZERO
                            : valuesMap.get(CURR_SECOND_HALF_LIB_CESS));
            jsonObject.addProperty("arrearLibraryTax",
                    valuesMap.get(ARR_LIB_CESS) == null ? BigDecimal.ZERO : valuesMap.get(ARR_LIB_CESS));
        }//  w w  w  .jav  a2 s .c o  m

        jsonObject.addProperty("propertyTaxSecondHlf",
                baseRegisterResultObj.getAggrCurrSecondHalfDmd() == null ? BigDecimal.ZERO
                        : baseRegisterResultObj.getAggrCurrSecondHalfDmd());

        jsonObject.addProperty("currTotal", currTotal);

        jsonObject.addProperty("penaltyFines", currPenaltyFine);
        jsonObject.addProperty("arrearPeriod",
                baseRegisterResultObj.getDuePeriod() != null
                        && org.apache.commons.lang.StringUtils.isNotBlank(baseRegisterResultObj.getDuePeriod())
                                ? baseRegisterResultObj.getDuePeriod()
                                : "NA");
        jsonObject.addProperty("arrearPropertyTax",
                baseRegisterResultObj.getAggrArrDmd() != null
                        && baseRegisterResultObj.getAggrArrDmd().compareTo(BigDecimal.ZERO) >= 1
                                ? baseRegisterResultObj.getAggrArrDmd().subtract(
                                        valuesMap == null ? BigDecimal.ZERO : valuesMap.get(ARR_LIB_CESS))
                                : BigDecimal.ZERO);
        jsonObject.addProperty("arrearPenaltyFines",
                baseRegisterResultObj.getAggrArrearPenaly() == null ? BigDecimal.ZERO
                        : baseRegisterResultObj.getAggrArrearPenaly());
        jsonObject.addProperty("arrearTotal", baseRegisterResultObj.getAggrArrDmd() == null ? BigDecimal.ZERO
                : baseRegisterResultObj.getAggrArrDmd());
        jsonObject.addProperty("arrearColl", arrColl);

        jsonObject.addProperty("currentColl", currentColl);
        jsonObject.addProperty("totalColl", totalColl);
        baseRegisterResultData.add(jsonObject);
    });
    return enhance(baseRegisterResultData, baseRegisterResponse);
}

From source file:org.jvnet.hudson.plugins.backup.utils.BackupTask.java

public void run() {
    assert (logFilePath != null);
    assert (configuration.getFileNameTemplate() != null);

    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);

    startDate = new Date();
    try {/*from w w  w  .  ja  v  a  2 s.  c  o  m*/
        logger = new BackupLogger(logFilePath, configuration.isVerbose());
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Unable to open log file for writing: {0}", logFilePath);
        return;
    }

    logger.info("Backup started at " + getTimestamp(startDate));

    // Have to include shutdown time in backup time ?
    waitNoJobsInQueue();

    // file filter specific to what's inside jobs' worskpace
    IOFileFilter jobsExclusionFileFilter = null;

    // Creating global exclusions
    List<String> exclusions = new ArrayList<String>();
    exclusions.addAll(Arrays.asList(DEFAULT_EXCLUSIONS));
    exclusions.addAll(configuration.getCustomExclusions());
    if (!configuration.getKeepWorkspaces()) {
        exclusions.add(WORKSPACE_NAME);
    } else {
        jobsExclusionFileFilter = createJobsExclusionFileFilter(hudsonWorkDir, configuration.getJobIncludes(),
                configuration.getJobExcludes(), configuration.getCaseSensitive());
    }
    if (!configuration.getKeepFingerprints()) {
        exclusions.add(FINGERPRINTS_NAME);
    }
    if (!configuration.getKeepBuilds()) {
        exclusions.add(BUILDS_NAME);
    }
    if (!configuration.getKeepArchives()) {
        exclusions.add(ARCHIVE_NAME);
    }

    IOFileFilter filter = createFileFilter(exclusions, jobsExclusionFileFilter);

    try {
        BackupEngine backupEngine = new BackupEngine(logger, hudsonWorkDir, backupFileName,
                configuration.getArchiveType().getArchiver(), filter);
        backupEngine.doBackup();
    } catch (BackupException e) {
        e.printStackTrace(logger.getWriter());
    } finally {
        cancelNoJobs();

        endDate = new Date();
        logger.info("Backup end at " + getTimestamp(endDate));
        BigDecimal delay = new BigDecimal(endDate.getTime() - startDate.getTime());
        delay = delay.setScale(2, BigDecimal.ROUND_HALF_UP);
        delay = delay.divide(new BigDecimal("1000"));

        logger.info("[" + delay.toPlainString() + "s]");

        finished = true;
        logger.close();
    }
}

From source file:org.jvnet.hudson.plugins.backup.utils.RestoreTask.java

public void run() {
    assert (logFilePath != null);
    assert (backupFileName != null);

    startDate = new Date();
    try {/* ww w .  jav a 2  s  .c  o m*/
        logger = new BackupLogger(logFilePath, configuration.isVerbose());
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Unable to open log file for writing : {0}", logFilePath);
        return;
    }

    logger.info("Restore started at " + getTimestamp(startDate));

    File directory = new File(hudsonWorkDir);

    String tempDirectoryPath = hudsonWorkDir + "_restore";
    logger.info("Working into " + tempDirectoryPath + " directory");

    File temporary_directory = new File(tempDirectoryPath);

    if (temporary_directory.exists()) {
        logger.info("A old restore working dir exists, cleaning ...");
        try {
            FileUtils.deleteDirectory(temporary_directory);
        } catch (IOException e) {
            logger.error("Unable to delete " + tempDirectoryPath);
            e.printStackTrace(logger.getWriter());
            finished = true;
            return;
        }
    }
    temporary_directory.mkdir();

    File archive = new File(backupFileName);

    logger.info("Uncompressing archive file...");
    UnArchiver unAchiver = configuration.getArchiveType().getUnArchiver();

    try {
        unAchiver.unArchive(archive, tempDirectoryPath);
    } catch (Exception e) {
        e.printStackTrace(logger.getWriter());
        logger.error("Error uncompressiong archive : " + e.getMessage());
        finished = true;
        return;
    }

    // Not using tools like FileUtils.deleteDirectory
    // because it is failing with non existing symbolic links
    logger.info("Removing old configuration files...");
    delete(directory);

    logger.info("Making temporary directory the hudson home...");
    temporary_directory.renameTo(directory);

    logger.info("*****************************************");
    logger.info("Reloading hudson configuration from disk.");
    logger.info("*****************************************");

    StaplerRequest request = FakeObject.getStaplerRequestFake(servletContext);
    StaplerResponse response = FakeObject.getStaplerResponseFake();

    try {
        Hudson.getInstance().doReload(request, response);
    } catch (IOException e) {
        logger.error("Error reloading config files from disk.");
        logger.error("Call this method manually");
        e.printStackTrace(logger.getWriter());
    }

    endDate = new Date();
    logger.info("Backup end at " + getTimestamp(endDate));
    BigDecimal delay = new BigDecimal(endDate.getTime() - startDate.getTime());
    delay = delay.setScale(2, BigDecimal.ROUND_HALF_UP);
    delay = delay.divide(new BigDecimal("1000"));

    logger.info("[" + delay.toPlainString() + "s]");
    finished = true;
    logger.close();
}

From source file:com.sun.faces.el.impl.DivideOperator.java

/**
 * Applies the operator to the given value
 *///  www.  jav a  2s.c o  m
public Object apply(Object pLeft, Object pRight) throws ElException {
    if (pLeft == null && pRight == null) {
        if (log.isWarnEnabled()) {
            log.warn(MessageUtil.getMessageWithArgs(Constants.ARITH_OP_NULL, getOperatorSymbol()));
        }
        return PrimitiveObjects.getInteger(0);
    }

    if (Coercions.isBigDecimal(pLeft) || Coercions.isBigInteger(pLeft) || Coercions.isBigDecimal(pRight)
            || Coercions.isBigInteger(pRight)) {

        BigDecimal left = (BigDecimal) Coercions.coerceToPrimitiveNumber(pLeft, BigDecimal.class);
        BigDecimal right = (BigDecimal) Coercions.coerceToPrimitiveNumber(pRight, BigDecimal.class);

        try {
            return left.divide(right, BigDecimal.ROUND_HALF_UP);
        } catch (Exception exc) {
            if (log.isErrorEnabled()) {
                String message = MessageUtil.getMessageWithArgs(Constants.ARITH_ERROR, getOperatorSymbol(),
                        "" + left, "" + right);
                log.error(message);
                throw new ElException(message);
            }
            return PrimitiveObjects.getInteger(0);
        }
    } else {

        double left = Coercions.coerceToPrimitiveNumber(pLeft, Double.class).doubleValue();
        double right = Coercions.coerceToPrimitiveNumber(pRight, Double.class).doubleValue();

        try {
            return PrimitiveObjects.getDouble(left / right);
        } catch (Exception exc) {
            if (log.isErrorEnabled()) {
                String message = MessageUtil.getMessageWithArgs(Constants.ARITH_ERROR, getOperatorSymbol(),
                        "" + left, "" + right);
                log.error(message);
                throw new ElException(message);
            }
            return PrimitiveObjects.getInteger(0);
        }
    }
}