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:geogebra.util.MyMath.java

/**
 * Round a double to the given number of digits
 * @param x //from w  w  w . j  av a  2 s  . c om
 * @param digits 
 * @return number rounded to given number of digits
 */
final public static double truncate(double x, int digits) {
    BigDecimal bd = new BigDecimal(x);
    bd = bd.setScale(digits, BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
}

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

public static Double round(Double d, int scale) {
    if (d == null || Double.isNaN(d)) {
        return d;
    }/*from   w  w w . ja v a 2  s  .c  om*/
    BigDecimal org = new BigDecimal(d);
    BigDecimal rounded = org.setScale(scale, BigDecimal.ROUND_HALF_UP);
    return rounded.doubleValue();
}

From source file:com.ms.app.web.commons.tools.CurrencyFormattor.java

/**
 * "###.####"-->"#.00" floatPrice-->formatPrice(?)
 *//*w w w  .j ava2s  .c o m*/
public static String float2formatPrice(Float price) {
    if (price == null) {
        return null;
    }

    BigDecimal b = new BigDecimal(price);
    float f = b.setScale(SCALE, BigDecimal.ROUND_HALF_UP).floatValue();
    DecimalFormat fnum = new DecimalFormat(CURRENCY);

    return fnum.format(f);
}

From source file:org.estatio.app.budget.Status.java

@Action(semantics = SemanticsOf.IDEMPOTENT, invokeOn = InvokeOn.OBJECT_AND_COLLECTION)
public BudgetKeyItem apply() {
    if (budgetKeyItem == null) {
        BudgetKeyItem budgetKeyItem = new BudgetKeyItem();
        budgetKeyItem.setBudgetKeyTable(budgetKeyTables.findBudgetKeyTableByName(getBudgetKeyTableName()));
        budgetKeyItem.setUnit(units.findUnitByReference(unitReference));
    }//from  w w w.  jav a  2  s.  c  o m
    budgetKeyItems
            .findByBudgetKeyTableAndUnit(budgetKeyTables.findBudgetKeyTableByName(getBudgetKeyTableName()),
                    units.findUnitByReference(unitReference))
            .changeKeyValue(this.getKeyValue().setScale(3, BigDecimal.ROUND_HALF_UP));
    budgetKeyItems
            .findByBudgetKeyTableAndUnit(budgetKeyTables.findBudgetKeyTableByName(getBudgetKeyTableName()),
                    units.findUnitByReference(unitReference))
            .changeAugmentedKeyValue(this.getAugmentedKeyValue().setScale(6, BigDecimal.ROUND_HALF_UP));
    budgetKeyItems
            .findByBudgetKeyTableAndUnit(budgetKeyTables.findBudgetKeyTableByName(getBudgetKeyTableName()),
                    units.findUnitByReference(unitReference))
            .setSourceValue(this.getSourceValue().setScale(2, BigDecimal.ROUND_HALF_UP));
    return budgetKeyItem;
}

From source file:com.siapa.managedbean.DetalleCompraAlimentoManagedBean.java

public void cargar() {
    try {/*from   w  w w . ja va  2s .co  m*/
        DetalleCompraAlimento nuevo = new DetalleCompraAlimento();
        nuevo = getDetalleCompraAlimento();
        nuevo.setSumaParcial(getTotal());
        nuevo.setIdAlimento(getAlimento());
        tablaDetalleAlimentoPojoLista.add(nuevo);
        if (tablaDetalleAlimentoPojoLista.isEmpty()) {
            flag = false;
        } else {
            flag = true;
        }
        sumaTotal = sumaTotal.add(getTotal().setScale(2, BigDecimal.ROUND_HALF_UP));
        detalleCompraAlimento = new DetalleCompraAlimento();

    } catch (Exception e) {
        System.out.println("error" + e);
    }
}

From source file:com.dianping.dpsf.jmx.DpsfRequestorMonitor.java

public ServiceInvokeStatsResult getServiceStats(int skip, int size) {
    try {/*from w ww  .  j ava2s . co m*/
        ServiceInvokeStatsResult statsResult = new ServiceInvokeStatsResult();
        Map<String, ServiceInvokeStats> serviceStats = new HashMap<String, ServiceInvokeStats>();
        Map<String, Set<HostInfo>> serviceHostInfos = clientManager.getServiceHostInfos();
        Map<String, Set<String>> service2Connects = new TreeMap<String, Set<String>>();
        Map<String, Set<String>> service2FullNames = new HashMap<String, Set<String>>();
        for (String serviceFullName : serviceHostInfos.keySet()) {
            String serviceName = getServiceName(serviceFullName);
            if (serviceName != null) {
                Set<String> connects = service2Connects.get(serviceName);
                if (connects == null) {
                    connects = new TreeSet<String>();
                    service2Connects.put(serviceName, connects);
                }
                Set<HostInfo> hostInfos = serviceHostInfos.get(serviceFullName);
                Iterator<HostInfo> iter = hostInfos.iterator();
                while (iter.hasNext()) {
                    connects.add(iter.next().getConnect());
                }
                if (!service2FullNames.containsKey(serviceName)) {
                    service2FullNames.put(serviceName, new HashSet<String>());
                }
                service2FullNames.get(serviceName).add(serviceFullName);
            }
        }
        int index = 0;
        for (Entry<String, Set<String>> entry : service2Connects.entrySet()) {
            if (index >= skip && index < skip + size) {
                String service = entry.getKey();
                serviceStats.put(service, new ServiceInvokeStats(index));
                for (String connect : entry.getValue()) {
                    ServiceInvokeStats serviceInvokeStats = serviceStats.get(service);
                    ServiceInvokeStat stat = new ServiceInvokeStat(connect);
                    if (RpcStatsPool.hasServerBarrel(connect)) {
                        ServiceBarrel serverBarrel = RpcStatsPool.getServerBarrel(connect);
                        /*
                         * ?consoleweight?connect, pigeon??service+connect, UI?service??,
                         * ???, service+connect?weight
                         */
                        stat.setCapacity(new BigDecimal(serverBarrel.getCapacity())
                                .setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
                        stat.setRequestSend(serverBarrel.getTotalRequest().longValue());
                        stat.setOnewayRequestSend(serverBarrel.getOnewayRequest().longValue());
                        stat.setRequestSendLastSec(serverBarrel.getLastSecondRequest());
                    }
                    stat.setWeight(getServiceWeight(service2FullNames, service, connect));
                    stat.setConnected(
                            !clientManager.getReconnectTask().getClosedClients().containsKey(connect));
                    Map<String, Client> allClients = clientManager.getClientCache().getAllClients();
                    if (allClients.containsKey(connect)) {
                        stat.setActive(allClients.get(connect).isActive());
                    }
                    serviceInvokeStats.addServiceStat(stat);
                }
            }
            index++;
        }
        statsResult.setStats(serviceStats);
        statsResult.setTotal(service2Connects.size());
        return statsResult;
    } catch (RuntimeException e) {
        logger.error("Get servicestats failed.", e);
        throw e;
    }
}

From source file:ch.algotrader.service.sim.SimulationOrderServiceImpl.java

/**
 * {@inheritDoc}/*from w w w.j a  v a 2  s. co m*/
 */
@Override
public BigDecimal getPrice(final SimpleOrder order) {

    Validate.notNull(order, "Order is null");

    if (order instanceof LimitOrderI) {

        // limit orders are executed at their limit price
        return ((LimitOrderI) order).getLimit();

    } else {

        Security security = order.getSecurity();

        // all other orders are executed the the market
        MarketDataEventVO marketDataEvent = this.marketDataCacheService
                .getCurrentMarketDataEvent(security.getId());
        return marketDataEvent
                .getMarketValue(Side.BUY.equals(order.getSide()) ? Direction.SHORT : Direction.LONG)
                .setScale(security.getSecurityFamily().getScale(), BigDecimal.ROUND_HALF_UP);
    }

}

From source file:com.griddynamics.jagger.engine.e1.scenario.DefaultWorkloadSuggestionMaker.java

@Override
public WorkloadConfiguration suggest(BigDecimal desiredTps, NodeTpsStatistics statistics, int maxThreads) {
    log.debug("Going to suggest workload configuration. desired tps {}. statistics {}", desiredTps, statistics);

    Table<Integer, Integer, Pair<Long, BigDecimal>> threadDelayStats = statistics.getThreadDelayStats();

    if (areEqual(desiredTps, BigDecimal.ZERO)) {
        return WorkloadConfiguration.with(0, 0);
    }/*www  .  j  av  a2 s .  c o  m*/

    if (threadDelayStats.isEmpty()) {
        throw new IllegalArgumentException("Cannot suggest workload configuration");
    }

    if (!threadDelayStats.contains(CALIBRATION_CONFIGURATION.getThreads(),
            CALIBRATION_CONFIGURATION.getDelay())) {
        log.debug("Statistics is empty. Going to return calibration info.");
        return CALIBRATION_CONFIGURATION;
    }
    if (threadDelayStats.size() == 2 && areEqual(threadDelayStats.get(1, 0).getSecond(), BigDecimal.ZERO)) {
        log.warn("No calibration info. Going to retry.");
        return CALIBRATION_CONFIGURATION;
    }

    Map<Integer, Pair<Long, BigDecimal>> noDelays = threadDelayStats.column(0);

    log.debug("Calculate next thread count");
    Integer threadCount = findClosestPoint(desiredTps, noDelays);

    if (threadCount == 0) {
        threadCount = 1;
    }

    if (threadCount > maxThreads) {
        log.warn("{} calculated max {} allowed", threadCount, maxThreads);
        threadCount = maxThreads;
    }

    int currentThreads = statistics.getCurrentWorkloadConfiguration().getThreads();
    int diff = threadCount - currentThreads;
    if (diff > maxDiff) {
        log.debug("Increasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        return WorkloadConfiguration.with(currentThreads + maxDiff, 0);
    }

    diff = currentThreads - threadCount;
    if (diff > maxDiff) {
        log.debug("Decreasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        if ((currentThreads - maxDiff) > 1) {
            return WorkloadConfiguration.with(currentThreads - maxDiff, 0);
        } else {
            return WorkloadConfiguration.with(1, 0);
        }
    }

    if (!threadDelayStats.contains(threadCount, 0)) {
        return WorkloadConfiguration.with(threadCount, 0);
    }

    // <delay, <timestamp,tps>>
    Map<Integer, Pair<Long, BigDecimal>> delays = threadDelayStats.row(threadCount);

    // not enough statistics to calculate
    if (delays.size() == 1) {
        int delay = 0;
        BigDecimal tpsFromStat = delays.get(0).getSecond();

        // try to guess
        // tpsFromStat can be zero if no statistics was captured till this time
        if ((tpsFromStat.compareTo(BigDecimal.ZERO) > 0) && (desiredTps.compareTo(BigDecimal.ZERO) > 0)) {

            BigDecimal oneSecond = new BigDecimal(TimeUtils.secondsToMillis(1));
            BigDecimal result = oneSecond.multiply(new BigDecimal(threadCount)).divide(desiredTps, 3,
                    BigDecimal.ROUND_HALF_UP);
            result = result.subtract(oneSecond.multiply(new BigDecimal(threadCount)).divide(tpsFromStat, 3,
                    BigDecimal.ROUND_HALF_UP));

            delay = result.intValue();
        }
        // to have some non zero point in statistics
        if (delay == 0) {
            delay = MIN_DELAY;
        }

        delay = checkDelayInRange(delay);
        return WorkloadConfiguration.with(threadCount, delay);
    }

    log.debug("Calculate next delay");
    Integer delay = findClosestPoint(desiredTps, threadDelayStats.row(threadCount));

    delay = checkDelayInRange(delay);
    return WorkloadConfiguration.with(threadCount, delay);

}

From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

private static double getDaysRuleRate(double rule, Trade trade, Date endDate) {
    String timeLimitUnit = trade.getTimeLimitUnit();
    double timeLimit = trade.getTimeLimit();
    double days = 0;
    if (LoanLimitUnitEnum.LOAN_BY_DAY.code().equals(timeLimitUnit)) {
        days = timeLimit;/*ww w.jav a2 s.  c  om*/
    } else if (LoanLimitUnitEnum.LOAN_BY_YEAR.code().equals(timeLimitUnit)) {
        days = timeLimit * YrdConstants.TimeRelativeConstants.DAYSOFAYEAR;
    } else {
        days = Math.round(timeLimit * YrdConstants.TimeRelativeConstants.DAYSOFAYEAR / 12);
    }
    //?? ??
    if (null != trade.getEffectiveDateTime()) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar endTime = Calendar.getInstance();
            if (null == endDate) {
                endTime.setTime(sdf.parse(sdf.format(Calendar.getInstance().getTime())));
            } else {
                endTime.setTime(sdf.parse(sdf.format(endDate)));
            }
            Calendar beginTime = Calendar.getInstance();
            beginTime.setTime(sdf.parse(sdf.format(trade.getEffectiveDateTime())));
            int cutDays = (int) ((endTime.getTimeInMillis() - beginTime.getTimeInMillis()) / 1000 / 60 / 60
                    / 24);
            days = days - cutDays;
            days = (days < 0 ? 0 : days);
        } catch (Exception e) {
            Logger logger = LoggerFactory.getLogger("get DiffDate");
            logger.error("conculate diffDate throw a exceptioin!");
            logger.error(e.getMessage());
        }
    }
    BigDecimal bg = new BigDecimal(rule / YrdConstants.TimeRelativeConstants.DAYSOFAYEAR * days);
    double daysRate = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    return daysRate;
}