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:com.wso2.mobile.mdm.api.DeviceInfo.java

/**
*Returns the string formatted value for the size
*/// w  w w  . j  av  a 2s  .c  o m
public double formatSizeGB(double total) {
    double amount = (total / gbDivider);
    BigDecimal bd = new BigDecimal(amount).setScale(2, RoundingMode.HALF_EVEN);
    amount = bd.doubleValue();
    return amount;
}

From source file:org.renjin.primitives.MathGroup.java

@Builtin
@Deferrable/*  www .j a v a2s . co  m*/
@DataParallel(value = PreserveAttributeStyle.ALL, passNA = true)
public static double round(double x, int digits) {
    // adapted from the nmath library, fround.c

    double sign;
    int dig;

    if (Double.isNaN(x) || Double.isNaN(digits)) {
        return x + digits;
    }
    if (!DoubleVector.isFinite(x)) {
        return x;
    }

    if (digits == Double.POSITIVE_INFINITY) {
        return x;
    } else if (digits == Double.NEGATIVE_INFINITY) {
        return 0.0;
    }

    if (digits > MAX_DIGITS) {
        digits = MAX_DIGITS;
    }
    dig = (int) Math.floor(digits + 0.5);

    if (x < 0.) {
        sign = -1.;
        x = -x;
    } else {
        sign = 1.;
    }
    if (dig == 0) {
        return sign * Math.rint(x);
    } else if (dig > 0) {
        // round to a specific number of decimal places
        return sign * new BigDecimal(x).setScale(digits, RoundingMode.HALF_EVEN).doubleValue();
    } else {
        // round to the nearest power of 10
        double pow10 = Math.pow(10., -dig);
        return sign * Math.rint(x / pow10) * pow10;
    }
}

From source file:com.wso2.mobile.mdm.api.DeviceInfo.java

public double formatSizeMB(double total) {
    double amount = (total / mbDivider);
    BigDecimal bd = new BigDecimal(amount).setScale(2, RoundingMode.HALF_EVEN);
    amount = bd.doubleValue();//  w  w  w  .  j  a va  2s.co m
    return amount;
}

From source file:net.sourceforge.fenixedu.domain.residence.StudentsPerformanceReport.java

private BigDecimal getA(final Student student) {
    return BigDecimal.ZERO.equals(getEnrolledECTS(student)) ? BigDecimal.ZERO
            : getApprovedECTS(student).divide(getEnrolledECTS(student), 2, RoundingMode.HALF_EVEN);
}

From source file:net.sourceforge.fenixedu.domain.residence.StudentsPerformanceReport.java

private BigDecimal getB(final Student student) {
    return getNumberOfApprovedCourses(student) == 0 ? BigDecimal.ZERO
            : new BigDecimal(getApprovedGradeValuesSum(student))
                    .divide(new BigDecimal(getNumberOfApprovedCourses(student)), 2, RoundingMode.HALF_EVEN);
}

From source file:net.alexjf.tmm.fragments.ImmedTransactionEditorFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_immedtransaction_editor, container, false);

    descriptionText = (EditText) v.findViewById(R.id.description_text);
    categoryButton = (SelectorButton) v.findViewById(R.id.category_button);
    executionDateButton = (Button) v.findViewById(R.id.executionDate_button);
    executionTimeButton = (Button) v.findViewById(R.id.executionTime_button);
    valueSignToggle = (SignToggleButton) v.findViewById(R.id.value_sign);
    valueText = (EditText) v.findViewById(R.id.value_text);
    currencyTextView = (TextView) v.findViewById(R.id.currency_label);
    transferCheck = (CheckBox) v.findViewById(R.id.transfer_check);
    transferPanel = (LinearLayout) v.findViewById(R.id.transfer_panel);
    transferMoneyNodeLabel = (TextView) v.findViewById(R.id.transfer_moneynode_label);
    transferMoneyNodeButton = (SelectorButton) v.findViewById(R.id.transfer_moneynode_button);
    transferConversionPanel = (LinearLayout) v.findViewById(R.id.transfer_conversion_panel);
    transferConversionAmountText = (EditText) v.findViewById(R.id.transfer_conversion_amount_value);
    transferConversionCurrencyLabel = (TextView) v.findViewById(R.id.transfer_conversion_amount_currency);
    addButton = (Button) v.findViewById(R.id.add_button);

    valueText.setRawInputType(InputType.TYPE_CLASS_NUMBER);

    FragmentManager fm = getFragmentManager();

    timePicker = (TimePickerFragment) fm.findFragmentByTag(TAG_TIMEPICKER);
    datePicker = (DatePickerFragment) fm.findFragmentByTag(TAG_DATEPICKER);

    if (timePicker == null) {
        timePicker = new TimePickerFragment();
    }//from  w ww.j  a v  a 2s .c om

    if (datePicker == null) {
        datePicker = new DatePickerFragment();
    }

    timePicker.setListener(this);
    datePicker.setListener(this);

    categoryButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            Intent intent = new Intent(view.getContext(), CategoryListActivity.class);
            intent.putExtra(CategoryListActivity.KEY_INTENTION, CategoryListActivity.INTENTION_SELECT);
            startActivityForResult(intent, REQCODE_CATEGORYCHOOSE);
        }
    });

    executionDateButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            try {
                datePicker.setDate(dateFormat.parse(executionDateButton.getText().toString()));
            } catch (ParseException e) {
            }
            datePicker.show(getFragmentManager(), TAG_DATEPICKER);
        }
    });

    executionTimeButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            try {
                timePicker.setTime(timeFormat.parse(executionTimeButton.getText().toString()));
            } catch (ParseException e) {
            }
            timePicker.show(getFragmentManager(), TAG_TIMEPICKER);
        }
    });

    valueSignToggle.setOnChangeListener(new SignToggleButton.SignToggleButtonListener() {
        @Override
        public void onChange(boolean isPositive) {
            if (isPositive) {
                transferMoneyNodeLabel.setText(getResources().getString(R.string.transfer_moneynode_from));
            } else {
                transferMoneyNodeLabel.setText(getResources().getString(R.string.transfer_moneynode_to));
            }
        }
    });

    transferCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton view, boolean checked) {
            if (checked) {
                transferPanel.setVisibility(View.VISIBLE);
            } else {
                transferPanel.setVisibility(View.GONE);
            }
        }

        ;
    });

    transferMoneyNodeButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            Intent intent = new Intent(view.getContext(), MoneyNodeListActivity.class);
            intent.putExtra(MoneyNodeListActivity.KEY_INTENTION, MoneyNodeListActivity.INTENTION_SELECT);

            ArrayList<MoneyNode> excludedMoneyNodes = new ArrayList<MoneyNode>();
            excludedMoneyNodes.add(currentMoneyNode);
            intent.putParcelableArrayListExtra(MoneyNodeListActivity.KEY_EXCLUDE, excludedMoneyNodes);
            startActivityForResult(intent, REQCODE_MONEYNODECHOOSE);
        }
    });

    addButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if (!validateInputFields()) {
                return;
            }

            String description = descriptionText.getText().toString().trim();
            boolean isTransfer = transferCheck.isChecked();

            Date executionDate;
            Date executionTime;
            Date executionDateTime;
            try {
                executionDate = dateFormat.parse(executionDateButton.getText().toString());
                executionTime = timeFormat.parse(executionTimeButton.getText().toString());
            } catch (ParseException e) {
                executionTime = executionDate = new Date();
            }

            executionDateTime = Utils.combineDateTime(executionDate, executionTime);

            Money value;

            try {
                Calculable calc = new ExpressionBuilder(valueText.getText().toString()).build();
                value = Money.of(currentMoneyNode.getCurrency(), calc.calculate(), RoundingMode.HALF_EVEN);
            } catch (Exception e) {
                Log.e("TMM", "Error calculating value expression: " + e.getMessage(), e);
                value = Money.zero(currentMoneyNode.getCurrency());
            }

            if (valueSignToggle.isNegative()) {
                value = value.negated();
            }

            Money currencyConversionValue = null;

            // If an amount was entered for conversion to other currency, set
            // value of transfer transaction to this amount
            if (isTransfer && !TextUtils.isEmpty(transferConversionAmountText.getText())) {
                try {
                    Calculable calc = new ExpressionBuilder(transferConversionAmountText.getText().toString())
                            .build();
                    currencyConversionValue = Money.of(selectedTransferMoneyNode.getCurrency(),
                            calc.calculate(), RoundingMode.HALF_EVEN);
                    currencyConversionValue = currencyConversionValue.abs();
                } catch (Exception e) {
                    Log.e("TMM", "Error calculating conversion amount expression: " + e.getMessage(), e);
                    currencyConversionValue = Money.zero(selectedTransferMoneyNode.getCurrency());
                }

                if (!valueSignToggle.isNegative()) {
                    currencyConversionValue = currencyConversionValue.negated();
                }
            }

            // If we are creating a new transaction
            if (transaction == null) {
                ImmediateTransaction newTransaction = new ImmediateTransaction(currentMoneyNode, value,
                        description, selectedCategory, executionDateTime);

                // If this new transaction is a transfer
                if (isTransfer && selectedTransferMoneyNode != null) {
                    ImmediateTransaction otherTransaction = new ImmediateTransaction(newTransaction,
                            selectedTransferMoneyNode);

                    // If a value was specified for the conversion to other currency,
                    // use that value instead of the negation of current one
                    if (currencyConversionValue != null) {
                        otherTransaction.setValue(currencyConversionValue);
                    }

                    newTransaction.setTransferTransaction(otherTransaction);
                    otherTransaction.setTransferTransaction(newTransaction);
                }

                listener.onImmediateTransactionCreated(newTransaction);
            }
            // If we are updating an existing transaction
            else {
                ImmedTransactionEditOldInfo oldInfo = new ImmedTransactionEditOldInfo(transaction);
                transaction.setDescription(description);
                transaction.setCategory(selectedCategory);
                transaction.setExecutionDate(executionDateTime);
                transaction.setValue(value);

                if (isTransfer && selectedTransferMoneyNode != null) {
                    ImmediateTransaction otherTransaction = null;

                    // If edited transaction wasn't part of a transfer and
                    // now is, create transfer transaction
                    if (transaction.getTransferTransaction() == null) {
                        otherTransaction = new ImmediateTransaction(transaction, selectedTransferMoneyNode);
                        transaction.setTransferTransaction(otherTransaction);
                        otherTransaction.setTransferTransaction(transaction);
                    }
                    // If edited transaction was already part of a
                    // transfer, update transfer transaction
                    else {
                        otherTransaction = transaction.getTransferTransaction();

                        otherTransaction.setMoneyNode(selectedTransferMoneyNode);
                        otherTransaction.setDescription(description);
                        otherTransaction.setCategory(selectedCategory);
                        otherTransaction.setExecutionDate(executionDateTime);
                        otherTransaction.setValue(value.negated());
                    }

                    // If a value was specified for the conversion to other currency,
                    // use that value instead of the negation of current one
                    if (currencyConversionValue != null) {
                        otherTransaction.setValue(currencyConversionValue);
                    }
                }
                // If edited transaction no longer is a transfer but
                // was a transfer before, we need to remove the opposite
                // transaction.
                else if (transaction.getTransferTransaction() != null) {
                    transaction.setTransferTransaction(null);
                }
                listener.onImmediateTransactionEdited(transaction, oldInfo);
            }
        }
    });

    this.savedInstanceState = savedInstanceState;

    return v;
}

From source file:gg.view.overview.IncomeExpensesTopComponent.java

/** Displays the total income vs expenses for the current month */
public void displayData() {
    log.info("Income vs Expenses graph computed and displayed");

    // Display hourglass cursor
    Utilities.changeCursorWaitStatus(true);

    // Create a dataset (the dataset will contain the plotted values)
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    // Create an empty chart
    JFreeChart chart = ChartFactory.createBarChart("", // chart title
            "", // x axis label
            NbBundle.getMessage(IncomeExpensesTopComponent.class, "IncomeExpensesTopComponent.Amount"), // y axis label
            dataset, // data displayed in the chart
            PlotOrientation.VERTICAL, false, // include legend
            true, // tooltips
            false // urls
    );//from w w  w  .  jav a 2  s.co  m

    // Update the chart color
    chart.setBackgroundPaint(jPanelIncomeExpenses.getBackground());
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);

    // Set the orientation of the categories on the domain axis (X axis)
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);

    // Set the range axis (Y axis) to display integers only
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // Set the bar renderer
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setMaximumBarWidth(0.1);

    GradientPaint gradientPaint = new GradientPaint(0.0f, 0.0f, new Color(49, 106, 196), 0.0f, 0.0f,
            Color.LIGHT_GRAY);
    renderer.setSeriesPaint(0, gradientPaint);

    // Create a period for the current month
    LocalDate today = new LocalDate();
    Period currentMonth = new Period(Periods.getAdjustedStartDate(today, PeriodType.MONTH),
            Periods.getAdjustedEndDate(today, PeriodType.MONTH), PeriodType.MONTH);

    // Fill the dataset
    List<Currency> currencies = Wallet.getInstance().getActiveCurrencies();
    for (Currency currency : currencies) {
        // Filter on the currency and on the current month
        SearchCriteria searchCriteria = new SearchCriteria(currency, null, currentMonth, null, null, null,
                false);

        // Get income
        BigDecimal currencyIncome = Datamodel.getIncome(searchCriteria);
        currencyIncome = currencyIncome.setScale(2, RoundingMode.HALF_EVEN);

        // Get expenses
        BigDecimal currencyExpenses = Datamodel.getExpenses(searchCriteria).abs();
        currencyExpenses = currencyExpenses.setScale(2, RoundingMode.HALF_EVEN);

        // Plot income and expenses for the current month and for the current currency on the chart
        dataset.addValue(currencyIncome, currency.getName(),
                NbBundle.getMessage(IncomeExpensesTopComponent.class, "IncomeExpensesTopComponent.Income",
                        new Object[] { currency }));

        dataset.addValue(currencyExpenses, currency.getName(),
                NbBundle.getMessage(IncomeExpensesTopComponent.class, "IncomeExpensesTopComponent.Expenses",
                        new Object[] { currency }));
    }

    // Create the chart panel that contains the chart
    ChartPanel chartPanel = new ChartPanel(chart);

    // Display the chart
    jPanelIncomeExpenses.removeAll();
    jPanelIncomeExpenses.add(chartPanel, BorderLayout.CENTER);

    // Display the normal cursor
    Utilities.changeCursorWaitStatus(false);
}

From source file:com.valco.utility.FacturasUtility.java

public static String getFacturaConSello(Facturas factura) throws Exception {

    Clientes cliente = factura.getNotasDeVenta().getClientes();
    String xml = null;// w w w .  j  a v  a2 s  .co  m
    try {
        xml = formaXmlFactura(factura.getSerie(), Integer.toString(factura.getFolio()), factura.getFecha(),
                factura.getFormaPago(), factura.getTotal().setScale(2, RoundingMode.HALF_EVEN).toString(),
                factura.getSubtotal().setScale(2, RoundingMode.HALF_EVEN).toString(), factura.getMoneda(),
                factura.getMetodoPago(), factura.getLugar(), cliente.getCuentaBancaria().toString(),
                factura.getNoSeieCertEmisor(), "ingreso", "AAA010101AAA",
                "DISTRIBUIDORA DE CARNES VALCO S.A. DE C.V.", "PARRAL", "246", "123", "REVOLUCION", "CHIHUAHUA",
                "referencia", "CHIHUAHUA", "CHIHUAHUA", "MXICO", "31110", "REGIMEN", cliente.getRfc(),
                cliente.getNombreCompleto(), cliente.getCalle(), Integer.toString(cliente.getNumeroExterior()),
                cliente.getNumeroInterior(), cliente.getColonia(), cliente.getCiudad(), cliente.getEstado(),
                cliente.getPais(), Integer.toString(cliente.getCodigoPostal()),
                factura.getConceptosFacturas().iterator(), factura.getImpuestoses());
    } catch (ParseException ex) {
        throw new Exception("Ocurri un error al formar el XML de la factura");
    }
    OutputStream cadenaOriginal = null;
    try {
        cadenaOriginal = getCadenaOriginal("C:/SAT/cadenaoriginal_3_2.xslt",
                new String(xml.getBytes("Windows-1252")));
    } catch (UnsupportedEncodingException ex) {
        throw new Exception("Ocurri un error al obtener la cadena original");
    }
    factura.setCadenaOriginal(cadenaOriginal.toString());
    byte[] bytesKey = null;
    java.security.PrivateKey pk = null;
    try {
        bytesKey = getBytesPrivateKey("C:/SAT/aaa010101aaa__csd_01.key");
        pk = getPrivateKey(bytesKey, "12345678a");
    } catch (GeneralSecurityException ex) {
        throw new Exception(ex);
    }
    byte[] bytesCadenaFirmada = null;
    try {
        bytesCadenaFirmada = getBytesCadenaFirmada(pk, cadenaOriginal);
    } catch (Exception ex) {
        throw new Exception("Ocurri un error al ofirmar la cadena original");
    }
    String selloBase64 = getSelloBase64(bytesCadenaFirmada);
    xml = xml.replace("AQUIVAELSELLO", selloBase64);
    return xml;

}

From source file:org.mayocat.shop.billing.internal.SendEmailsWhenOrderIsPaid.java

/**
 * Prepares the JSON context for an order mail notification
 *
 * @param order the order concerned by the notification
 * @param customer the customer/* w  w  w  .j av a  2s  . c  o m*/
 * @param ba an optional billing address
 * @param da an optional shipping address
 * @param tenant the tenant the order was checked out from
 * @param locale the main locale of the tenant
 * @return a JSON context as map
 */
private Map<String, Object> prepareMailContext(Order order, Customer customer, Optional<Address> ba,
        Optional<Address> da, Tenant tenant, Locale locale) {
    List<OrderItem> items = order.getOrderItems();
    Map<String, Object> context = Maps.newHashMap();

    MoneyFormatter formatter = new MoneyFormatterBuilder().appendAmount(MoneyAmountStyle.of(locale))
            .appendLiteral(" ").appendCurrencySymbolLocalized().toFormatter();

    CurrencyUnit currencyUnit = CurrencyUnit.of(order.getCurrency());
    String grandTotal = formatter.withLocale(locale)
            .print(Money.of(currencyUnit, order.getGrandTotal(), RoundingMode.HALF_EVEN));
    String itemsTotal = formatter.withLocale(locale)
            .print(Money.of(currencyUnit, order.getItemsTotal(), RoundingMode.HALF_EVEN));

    List<Map<String, Object>> itemsData = Lists.newArrayList();

    for (OrderItem item : items) {
        // Replace big decimal values by formatted values
        Map<String, Object> itemData = Maps.newHashMap();
        itemData.put("unitPrice", formatter.withLocale(locale)
                .print(Money.of(currencyUnit, item.getUnitPrice(), RoundingMode.HALF_EVEN)));
        itemData.put("itemTotal", formatter.withLocale(locale)
                .print(Money.of(currencyUnit, item.getItemTotal(), RoundingMode.HALF_EVEN)));
        itemData.put("title", item.getTitle());
        itemData.put("quantity", item.getQuantity());
        itemData.put("vatRate", item.getVatRate().longValue());
        itemsData.add(itemData);
    }

    context.put("items", itemsData);

    if (order.getShipping() != null) {
        String shippingTotal = formatter.withLocale(locale)
                .print(Money.of(currencyUnit, order.getShipping(), RoundingMode.HALF_EVEN));
        context.put("shippingTotal", shippingTotal);
        context.put("shipping", order.getOrderData().get("shipping"));
    }

    String siteName;
    if (tenant != null) {
        siteName = Strings.isNullOrEmpty(tenant.getName()) ? tenant.getSlug() : tenant.getName();
    } else {
        siteName = siteSettings.getName();
    }
    context.put("siteName", siteName);
    context.put("itemsTotal", itemsTotal);
    context.put("orderId", order.getSlug());
    context.put("grandTotal", grandTotal);
    context.put("additionalInformation", order.getAdditionalInformation());
    context.put("orderDate", new DateWebObject().withDate(order.getCreationDate(), locale));

    Map<String, Object> customerMap = Maps.newHashMap();
    customerMap.put("firstName", customer.getFirstName());
    customerMap.put("lastName", customer.getLastName());
    customerMap.put("email", customer.getEmail());
    customerMap.put("phone", customer.getPhoneNumber());
    context.put("customer", customerMap);

    if (ba.isPresent()) {
        context.put("billingAddress", prepareAddressContext(ba.get()));
    }
    if (da.isPresent()) {
        context.put("deliveryAddress", prepareAddressContext(da.get()));
    }

    context.put("siteUrl", urlHelper.getTenantWebURL(tenant, "").toString());
    context.put("backOfficeUrl", urlHelper.getTenantBackOfficeURL(tenant, "").toString());

    return context;
}

From source file:com.benfante.minimark.po.Assessment.java

@Transient
public BigDecimal getQuestionsTotalWeight() {
    double result = 0;
    for (AssessmentQuestion assessmentQuestion : getQuestions()) {
        final Question question = assessmentQuestion.getQuestion();
        if (question.getWeight() != null) {
            result += question.getWeight().doubleValue();
        }//w  ww. j  a  v  a2 s .  co m
    }
    final BigDecimal bdResult = BigDecimal.valueOf(result);
    bdResult.setScale(2, RoundingMode.HALF_EVEN);
    return bdResult;
}