Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

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

Prototype

RoundingMode HALF_UP

To view the source code for java.math RoundingMode 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:org.talend.dataprep.transformation.actions.math.TemperaturesConverter.java

@Override
protected String calculateResult(String columnValue, ActionContext context) {
    TemperatureUnit fromTemperatureUnit = TemperatureUnit
            .valueOf(context.getParameters().get(FROM_UNIT_PARAMETER));
    TemperatureUnit toTemperatureUnit = TemperatureUnit.valueOf(context.getParameters().get(TO_UNIT_PARAMETER));
    String precisionParameter = context.getParameters().get(TARGET_PRECISION);

    BigDecimal value = BigDecimalParser.toBigDecimal(columnValue);
    TemperatureImpl fromTemp = new TemperatureImpl(value, fromTemperatureUnit.asJavaUnit());
    TemperatureImpl temperature = fromTemp.convertTo(toTemperatureUnit.asJavaUnit());

    // Precision is used as scale, for precision as significant digits, see history
    Integer targetScale = NumberUtils.toInt(precisionParameter, value.scale());

    return temperature.getValue().setScale(targetScale, RoundingMode.HALF_UP).toPlainString();
}

From source file:services.kpi.PortfolioEntryProgressKpi.java

@Override
public BigDecimal computeMain(IPreferenceManagerPlugin preferenceManagerPlugin, IScriptService scriptService,
        Kpi kpi, Long objectId) {
    PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(objectId);

    BigDecimal numerator = BigDecimal.ZERO;
    BigDecimal denominator = BigDecimal.ZERO;
    BigDecimal value = new BigDecimal(100);

    for (PortfolioEntryPlanningPackage planningPackage : portfolioEntry.planningPackages) {

        BigDecimal days = PortfolioEntryResourcePlanDAO
                .getPEPlanAllocatedActorAsDaysByPlanningPackage(planningPackage)
                .add(PortfolioEntryResourcePlanDAO
                        .getPEResourcePlanAllocatedOrgUnitAsDaysByPlanningPackage(planningPackage))
                .add(PortfolioEntryResourcePlanDAO
                        .getPEResourcePlanAllocatedCompetencyAsDaysByPlanningPackage(planningPackage));

        denominator = denominator.add(days);

        switch (planningPackage.status) {
        case CLOSED:
            numerator = numerator.add(days);
            break;
        case ON_GOING:
            numerator = numerator.add(days.multiply(getOnGoingRate(preferenceManagerPlugin)));
            break;
        default://from   w  w w  .ja  va 2 s .c om
            break;
        }

    }

    if (!denominator.equals(BigDecimal.ZERO)) {
        value = numerator.divide(denominator, RoundingMode.HALF_UP).multiply(value);
    }

    return value;
}

From source file:edu.umm.radonc.ca_dash.controllers.PieChartController.java

public PieChartController() {
    endDate = new Date();
    this.interval = "";

    GregorianCalendar gc = new GregorianCalendar();
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    Map<String, Object> sessionMap = externalContext.getSessionMap();

    if (sessionMap.containsKey("endDate")) {
        endDate = (Date) sessionMap.get("endDate");
    } else {/*from w w  w  .j  a  v  a  2  s . c  om*/
        endDate = new Date();
        sessionMap.put("endDate", endDate);
    }

    if (sessionMap.containsKey("startDate")) {
        startDate = (Date) sessionMap.get("startDate");
    } else {
        gc.setTime(endDate);
        gc.add(Calendar.MONTH, -1);
        startDate = gc.getTime();
        sessionMap.put("startDate", startDate);
        this.interval = "1m";
    }

    this.df = new SimpleDateFormat("MM/dd/YYYY");
    this.decf = new DecimalFormat("###.###");
    this.decf.setRoundingMode(RoundingMode.HALF_UP);
    this.selectedFacility = new Long(-1);
    this.dstats = new SynchronizedDescriptiveStatistics();
    this.dstatsPerDoc = new TreeMap<>();
    this.dstatsPerRTM = new TreeMap<>();
    this.pieChart = new PieChartModel();

    selectedFilters = "all-tx";
}

From source file:org.openconcerto.erp.graph.GraphFamilleArticlePanel.java

public GraphFamilleArticlePanel(Date d1, Date d2) {
    this.d1 = d1;
    this.d2 = d2;
    List<String> labels = new ArrayList<String>();
    List<Number> values = new ArrayList<Number>();
    BigDecimal total = updateDataset(labels, values);
    PieChart chart = new PieChart();
    chart.setDimension(new Dimension(800, 360));
    chart.setData(values);//  w ww .j  a  va 2 s. com
    for (String label : labels) {
        chart.addLabel(new Label(label));
    }

    ChartPanel p = new ChartPanel(chart);
    this.setLayout(new GridBagLayout());
    final GridBagConstraints c = new DefaultGridBagConstraints();
    c.insets = new Insets(4, 6, 4, 4);
    p.setOpaque(false);
    this.setBackground(Color.WHITE);
    this.add(p, c);

    final JPanel p1 = new JPanel();
    p1.setOpaque(false);
    p1.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy");
    p1.add(new JLabelBold("Rpartition du chiffre d'affaire du " + format.format(d1) + " au "
            + format.format(d2) + " pour un total de "
            + decFormat.format(total.setScale(2, RoundingMode.HALF_UP).doubleValue()) + ""));

    c.gridy++;
    c.weighty = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.NORTHWEST;
    this.add(p1, c);
}

From source file:org.gradle.performance.measure.DataSeries.java

public DataSeries(Iterable<? extends Amount<Q>> values) {
    for (Amount<Q> value : values) {
        if (value != null) {
            add(value);//from   w  w w .j av  a2  s. com
        }
    }

    if (isEmpty()) {
        average = null;
        median = null;
        max = null;
        min = null;
        standardError = null;
        return;
    }

    Amount<Q> total = get(0);
    Amount<Q> min = get(0);
    Amount<Q> max = get(0);
    for (int i = 1; i < size(); i++) {
        Amount<Q> amount = get(i);
        total = total.plus(amount);
        min = min.compareTo(amount) <= 0 ? min : amount;
        max = max.compareTo(amount) >= 0 ? max : amount;
    }
    List<Amount<Q>> sorted = Lists.newArrayList(this);
    Collections.sort(sorted);
    Amount<Q> medianLeft = sorted.get((sorted.size() - 1) / 2);
    Amount<Q> medianRight = sorted.get((sorted.size() - 1) / 2 + 1 - sorted.size() % 2);
    median = medianLeft.plus(medianRight).div(2);
    average = total.div(size());
    this.min = min;
    this.max = max;

    BigDecimal sumSquares = BigDecimal.ZERO;
    Units<Q> baseUnits = average.getUnits().getBaseUnits();
    BigDecimal averageValue = average.toUnits(baseUnits).getValue();
    for (int i = 0; i < size(); i++) {
        Amount<Q> amount = get(i);
        BigDecimal diff = amount.toUnits(baseUnits).getValue();
        diff = diff.subtract(averageValue);
        diff = diff.multiply(diff);
        sumSquares = sumSquares.add(diff);
    }
    // This isn't quite right, as we may lose precision when converting to a double
    BigDecimal result = BigDecimal
            .valueOf(Math
                    .sqrt(sumSquares.divide(BigDecimal.valueOf(size()), RoundingMode.HALF_UP).doubleValue()))
            .setScale(2, RoundingMode.HALF_UP);

    standardError = Amount.valueOf(result, baseUnits);
}

From source file:feedme.model.Order.java

public double round(double value, int places) {
    if (places < 0)
        throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

From source file:enterprises.orbital.evekit.model.corporation.sync.ESICorporationIndustryJobSync.java

@SuppressWarnings("RedundantThrows")
@Override//from  w w  w . j ava 2s  . c om
protected void processServerData(long time,
        ESIAccountServerResult<List<GetCorporationsCorporationIdIndustryJobs200Ok>> data,
        List<CachedData> updates) throws IOException {
    // Add and record orders
    for (GetCorporationsCorporationIdIndustryJobs200Ok next : data.getData()) {
        IndustryJob nextJob = new IndustryJob(next.getJobId(), next.getInstallerId(), next.getFacilityId(),
                next.getLocationId(), next.getActivityId(), next.getBlueprintId(), next.getBlueprintTypeId(),
                next.getBlueprintLocationId(), next.getOutputLocationId(), next.getRuns(),
                BigDecimal.valueOf(nullSafeDouble(next.getCost(), 0D)).setScale(2, RoundingMode.HALF_UP),
                nullSafeInteger(next.getLicensedRuns(), 0), nullSafeFloat(next.getProbability(), 0F),
                nullSafeInteger(next.getProductTypeId(), 0), next.getStatus().toString(), next.getDuration(),
                next.getStartDate().getMillis(), next.getEndDate().getMillis(),
                nullSafeDateTime(next.getPauseDate(), new DateTime(new Date(0L))).getMillis(),
                nullSafeDateTime(next.getCompletedDate(), new DateTime(new Date(0L))).getMillis(),
                nullSafeInteger(next.getCompletedCharacterId(), 0),
                nullSafeInteger(next.getSuccessfulRuns(), 0));
        updates.add(nextJob);
    }
}

From source file:org.projectforge.business.gantt.GanttUtils.java

private static Date getCalculatedStartDate(final GanttTask node, final Set<Serializable> startDateSet,
        final Set<Serializable> endDateSet) {
    if (node == null) {
        return null;
    }//from  w  ww.ja  v  a 2s.co  m
    if (node.getStartDate() != null) {
        return node.getStartDate();
    }
    if (node.isStartDateCalculated() == true) {
        return node.getCalculatedStartDate();
    }
    final int durationDays = node.getDuration() != null
            ? node.getDuration().setScale(0, RoundingMode.HALF_UP).intValue()
            : 0;
    if (node.getDuration() != null && node.getEndDate() != null) {
        final Date startDate = calculateDate(node.getEndDate(), -durationDays);
        node.setCalculatedStartDate(startDate).setStartDateCalculated(true);
        if (log.isDebugEnabled() == true) {
            log.debug("calculated start date=" + startDate + " for: " + node);
        }
        return startDate;
    }
    if (startDateSet.contains(node.getId()) == true) {
        log.error("Circular reference detection (couldn't calculate start date: " + node);
        return null;
    } else {
        startDateSet.add(node.getId());
    }
    Date startDate = null;
    final GanttTask predecessor = node.getPredecessor();
    if (predecessor != null) {
        startDate = getPredecessorRelDate(node.getRelationType(), predecessor, startDateSet, endDateSet);
        if (startDate != null) {
            if (NumberHelper.isNotZero(node.getPredecessorOffset()) == true) {
                startDate = calculateDate(startDate, node.getPredecessorOffset());
            }
            if (node.getRelationType() == GanttRelationType.START_FINISH
                    || node.getRelationType() == GanttRelationType.FINISH_FINISH) {
                if (durationDays > 0) {
                    startDate = calculateDate(startDate, -durationDays);
                }
            }
        }
    }
    if ((predecessor == null || (node.getRelationType() != null && node.getRelationType()
            .isIn(GanttRelationType.FINISH_FINISH, GanttRelationType.START_FINISH) == true))
            && node.getChildren() != null) {
        // Calculate start date from the earliest child.
        for (final GanttTask child : node.getChildren()) {
            final Date date = getCalculatedStartDate(child, startDateSet, endDateSet);
            if (startDate == null) {
                startDate = date;
            } else if (date != null && date.before(startDate) == true) {
                if (log.isDebugEnabled() == true) {
                    log.debug("Start date of child is before start date=" + date + " of parent: " + child);
                }
                startDate = date;
            }
        }
    }
    if (startDate == null && node.getDuration() != null) {
        final Date calculatedEndDate = getCalculatedEndDate(node, startDateSet, endDateSet);
        if (calculatedEndDate != null) {
            startDate = calculateDate(calculatedEndDate, -durationDays);
        }
    }
    node.setCalculatedStartDate(startDate).setStartDateCalculated(true);
    if (log.isDebugEnabled() == true) {
        log.debug("calculated start date=" + startDate + " for: " + node);
    }
    return startDate;
}

From source file:io.github.lucaseasedup.logit.config.Property.java

public String getStringifiedValue() {
    switch (type) {
    case DOUBLE://w  ww  .  j  a  v a2s. c om
        return "~" + new BigDecimal(getDouble()).setScale(2, RoundingMode.HALF_UP);

    default:
        return value.toString();
    }
}

From source file:org.mifos.config.AccountingRulesIntegrationTest.java

@Test
public void testGetCurrencyRoundingMode() {
    RoundingMode configuredMode = AccountingRules.getCurrencyRoundingMode();
    String roundingMode = "FLOOR";
    RoundingMode configRoundingMode = RoundingMode.FLOOR;
    ConfigurationManager configMgr = ConfigurationManager.getInstance();
    configMgr.setProperty(AccountingRulesConstants.CURRENCY_ROUNDING_MODE, roundingMode);
    // return value from accounting rules class has to be the value defined
    // in the config file
    Assert.assertEquals(configRoundingMode, AccountingRules.getCurrencyRoundingMode());
    // clear the RoundingRule property from the config file so should get
    // the default value
    configMgr.clearProperty(AccountingRulesConstants.CURRENCY_ROUNDING_MODE);
    RoundingMode defaultValue = AccountingRules.getCurrencyRoundingMode();
    Assert.assertEquals(defaultValue, RoundingMode.HALF_UP);
    // now set a wrong rounding mode in config
    roundingMode = "UP";
    configMgr.addProperty(AccountingRulesConstants.CURRENCY_ROUNDING_MODE, roundingMode);
    try {/*from  ww  w  .  ja  va  2 s.  co  m*/
        AccountingRules.getCurrencyRoundingMode();
    } catch (RuntimeException e) {
        Assert.assertEquals(e.getMessage(),
                "CurrencyRoundingMode defined in the config file is not CEILING, FLOOR, HALF_UP. It is "
                        + roundingMode);
    }
    // save it back
    configMgr.setProperty(AccountingRulesConstants.CURRENCY_ROUNDING_MODE, configuredMode.toString());

}