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.valco.utility.FacturasUtility.java

public static Set<ConceptosFactura> convierteProductosAConceptos(Iterator<ProductosInventario> productos) {
    Set<ConceptosFactura> conceptos = new HashSet<>();
    while (productos.hasNext()) {
        ProductosInventario producto = productos.next();
        ConceptosFactura concepto = new ConceptosFactura();
        concepto.setPrecioUnitario(new BigDecimal("0.00").setScale(3, RoundingMode.HALF_EVEN));

        concepto.setClave(producto.getProductosHasProveedores().getProductos().getCodigo());
        concepto.setCantidad(new BigDecimal("1.00").setScale(2, RoundingMode.HALF_EVEN));
        concepto.setDescripcion(producto.getProductosHasProveedores().getProductos().getDescripcion());
        concepto.setPrecioUnitario(producto.getPrecio());
        concepto.setCantidad(producto.getPeso());
        concepto.setUnidad("KG");
        concepto.setImporteTotal(producto.getPrecio().multiply(producto.getPeso()));
        if (!conceptos.contains(concepto)) {
            conceptos.add(concepto);/*www .j  a  v  a 2 s  .  com*/
        } else {
            for (ConceptosFactura conceptoRepetio : conceptos) {
                if (conceptoRepetio.equals(concepto)) {
                    conceptoRepetio.setCantidad(conceptoRepetio.getCantidad().add(concepto.getCantidad()));
                    conceptoRepetio
                            .setImporteTotal(conceptoRepetio.getImporteTotal().add(concepto.getImporteTotal()));
                }
            }
        }
    }
    return conceptos;
}

From source file:org.mifosplatform.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Transactional
private void postInterest(final SavingsAccount account) {
    final Set<Long> existingTransactionIds = new HashSet<Long>();
    final Set<Long> existingReversedTransactionIds = new HashSet<Long>();
    updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);
    final LocalDate today = DateUtils.getLocalDateOfTenant();
    final MathContext mc = new MathContext(10, RoundingMode.HALF_EVEN);

    account.postInterest(mc, today);/*from  w  ww .  j a va 2s.c o  m*/
    this.savingAccountRepository.save(account);

    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);
}

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

public static void calculaTotalImpuestos(Set<Impuestos> impuestos, BigDecimal subTotal) {
    for (Impuestos impuesto : impuestos) {
        impuesto.setImporte(impuesto.getTasa().divide(new BigDecimal("100.00")).multiply(subTotal).setScale(2,
                RoundingMode.HALF_EVEN));
    }//from w  w w . j  a v  a  2 s.  c om
}

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

public static BigDecimal getTotalImpuestos(Set<Impuestos> impuestos) {
    BigDecimal totalImpuesto = new BigDecimal("0.000000");
    for (Impuestos impuesto : impuestos) {
        totalImpuesto = totalImpuesto.add(impuesto.getImporte()).setScale(6, RoundingMode.HALF_EVEN);
    }//from  www .  jav a2  s.  com
    return totalImpuesto;
}

From source file:uk.ac.leeds.ccg.andyt.projects.moses.process.Comparison.java

public void compareCASUV003WithCAS001() throws Exception {
    File infile;//  ww  w. jav  a2  s .co  m
    infile = new File("C:/Work/Projects/MoSeS/Workspace/UV003.dat");
    CASUV003DataHandler cASUV003DataHandler = new CASUV003DataHandler(infile);
    infile = new File("C:/Work/Projects/MoSeS/Workspace/CAS001.dat");
    CAS001DataHandler tCAS001DataHandler = new CAS001DataHandler(infile);

    CASUV003DataRecord aCASUV003DataRecord;
    CAS001DataRecord aCAS001DataRecord;
    long difference;
    long maxDifference = Long.MIN_VALUE;
    long sumOfSquaredDifference = 0L;
    long totalDifference = 0L;
    long absoluteDifference = 0L;
    long totalAbsoluteDifference = 0L;
    long RecordID;
    long nRecords = cASUV003DataHandler.getNDataRecords();
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        difference = (long) (aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        if (difference < 0) {
            absoluteDifference = difference * -1L;
        }
        sumOfSquaredDifference += (difference * difference);
        maxDifference = Math.max(maxDifference, difference);
        totalDifference += difference;
        totalAbsoluteDifference += absoluteDifference;
    }
    int scale = 100;
    int roundingMode = BigDecimal.ROUND_HALF_EVEN;
    BigDecimal nRecordsBigDecimal = new BigDecimal(nRecords);
    BigDecimal meanDifferenceBigDecimal = new BigDecimal(maxDifference).divide(nRecordsBigDecimal, scale,
            roundingMode);
    System.out.println("nRecords " + nRecords);
    System.out.println("meanDifferenceBigDecimal " + meanDifferenceBigDecimal.toString());
    System.out.println("sumOfSquaredDifference " + sumOfSquaredDifference);
    System.out.println("maxDifference " + maxDifference);
    System.out.println("totalAbsoluteDifference " + totalAbsoluteDifference);
    System.out.println("totalDifference " + totalDifference);
    BigDecimal standardDeviationOfDifferenceBigDecimal = new BigDecimal("0");
    BigDecimal differenceBigDecimal;
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        differenceBigDecimal = new BigDecimal(
                aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        standardDeviationOfDifferenceBigDecimal = differenceBigDecimal.multiply(differenceBigDecimal);
    }
    standardDeviationOfDifferenceBigDecimal = standardDeviationOfDifferenceBigDecimal
            .divide(nRecordsBigDecimal.subtract(BigDecimal.ONE), scale, roundingMode);
    standardDeviationOfDifferenceBigDecimal = Generic_BigDecimal.sqrt(standardDeviationOfDifferenceBigDecimal,
            scale, RoundingMode.HALF_EVEN);
    System.out.println("standardDeviationOfDifferenceBigDecimal " + standardDeviationOfDifferenceBigDecimal);
}

From source file:org.mifosplatform.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Override
public CommandProcessingResult undoTransaction(final Long savingsId, final Long transactionId,
        final boolean allowAccountTransferModification) {

    final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId);
    final Set<Long> existingTransactionIds = new HashSet<Long>();
    final Set<Long> existingReversedTransactionIds = new HashSet<Long>();
    updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);

    final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository
            .findOneByIdAndSavingsAccountId(transactionId, savingsId);
    if (savingsAccountTransaction == null) {
        throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId);
    }//from  w w  w  . j  a  v a  2 s  .c o  m

    if (!allowAccountTransferModification && this.accountTransfersReadPlatformService
            .isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)) {
        throw new PlatformServiceUnavailableException(
                "error.msg.saving.account.transfer.transaction.update.not.allowed",
                "Savings account transaction:" + transactionId
                        + " update not allowed as it involves in account transfer",
                transactionId);
    }

    final LocalDate today = DateUtils.getLocalDateOfTenant();
    final MathContext mc = new MathContext(15, RoundingMode.HALF_EVEN);

    if (account.isNotActive()) {
        throwValidationForActiveStatus(SavingsApiConstants.undoTransactionAction);
    }
    account.undoTransaction(transactionId);

    // undoing transaction is withdrawal then undo withdrawal fee
    // transaction if any
    if (savingsAccountTransaction.isWithdrawal()) {
        final SavingsAccountTransaction nextSavingsAccountTransaction = this.savingsAccountTransactionRepository
                .findOneByIdAndSavingsAccountId(transactionId + 1, savingsId);
        if (nextSavingsAccountTransaction != null
                && nextSavingsAccountTransaction.isWithdrawalFeeAndNotReversed()) {
            account.undoTransaction(transactionId + 1);
        }
    }

    checkClientOrGroupActive(account);
    if (savingsAccountTransaction.isPostInterestCalculationRequired()
            && account.isBeforeLastPostingPeriod(savingsAccountTransaction.transactionLocalDate())) {
        account.postInterest(mc, today);
    } else {
        account.calculateInterestUsing(mc, today);
    }
    account.validateAccountBalanceDoesNotBecomeNegative(SavingsApiConstants.undoTransactionAction);
    account.activateAccountBasedOnBalance();
    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);

    return new CommandProcessingResultBuilder() //
            .withEntityId(savingsId) //
            .withOfficeId(account.officeId()) //
            .withClientId(account.clientId()) //
            .withGroupId(account.groupId()) //
            .withSavingsId(savingsId) //
            .build();
}

From source file:org.mifosplatform.portfolio.savings.domain.SavingsAccountCharge.java

private BigDecimal percentageOf(final BigDecimal value, final BigDecimal percentage) {

    BigDecimal percentageOf = BigDecimal.ZERO;

    if (isGreaterThanZero(value)) {
        final MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
        final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc);
        percentageOf = value.multiply(multiplicand, mc);
    }/*from   w  w  w . j a va2  s.co m*/

    return percentageOf;
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private Payment convertToSAFTPaymentDocument(SettlementNote document,
        Map<String, oecd.standardauditfile_tax.pt_1.Customer> baseCustomers,
        Map<String, oecd.standardauditfile_tax.pt_1.Product> productMap) {
    Payment payment = new Payment();

    // Find the Customer in BaseCustomers
    oecd.standardauditfile_tax.pt_1.Customer customer = null;

    if (baseCustomers.containsKey(document.getDebtAccount().getCustomer().getCode())) {
        customer = baseCustomers.get(document.getDebtAccount().getCustomer().getCode());
    } else {/*from  ww w  .ja v a 2s .c o  m*/
        // If not found, create a new one and add it to baseCustomers
        customer = convertCustomerToSAFTCustomer(document.getDebtAccount().getCustomer());
        baseCustomers.put(customer.getCustomerID(), customer);
    }

    // MovementDate
    DatatypeFactory dataTypeFactory;
    try {
        dataTypeFactory = DatatypeFactory.newInstance();
        DateTime documentDate = document.getDocumentDate();

        // SystemEntryDate
        payment.setSystemEntryDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        payment.setTransactionDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        // DocumentNumber
        payment.setPaymentRefNo(document.getUiDocumentNumber());

        // CustomerID
        payment.setCustomerID(document.getDebtAccount().getCustomer().getCode());

        // DocumentStatus
        /*
         * Deve ser preenchido com: ?N? ? Normal; Texto 1 ?T? ? Por conta de
         * terceiros; ?A? ? Documento anulado.
         */
        SourceDocuments.Payments.Payment.DocumentStatus status = new SourceDocuments.Payments.Payment.DocumentStatus();
        if (document.isAnnulled()) {
            status.setPaymentStatus("A");
        } else {
            status.setPaymentStatus("N");
        }
        status.setPaymentStatusDate(payment.getSystemEntryDate());
        // status.setReason("");
        // Utilizador responsvel pelo estado atual do docu-mento.
        status.setSourceID(document.getVersioningUpdatedBy());
        // Deve ser preenchido com:
        // 'P' - Documento produzido na aplicacao;
        if (Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getExternSeries())
                || Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getLegacy())) {
            status.setSourcePayment(SAFTPTSourcePayment.I);
        } else {
            status.setSourcePayment(SAFTPTSourcePayment.P);
        }

        payment.setDocumentStatus(status);

        //Check if is Rehimbursement/Payment
        if (Constants.isPositive(document.getTotalPayedAmount())) {
            //PaymentMethods
            for (PaymentEntry paymentEntry : document.getPaymentEntriesSet()) {
                PaymentMethod method = new PaymentMethod();
                method.setPaymentAmount(paymentEntry.getPayedAmount().setScale(2, RoundingMode.HALF_EVEN));
                method.setPaymentDate(payment.getTransactionDate());
                method.setPaymentMechanism(convertToSAFTPaymentMechanism(paymentEntry.getPaymentMethod()));
                payment.getPaymentMethod().add(method);
            }
            payment.setSettlementType(SAFTPTSettlementType.NL);
        } else if (Constants.isPositive(document.getTotalReimbursementAmount())) {
            //Reimbursments
            for (ReimbursementEntry reimbursmentEntry : document.getReimbursementEntriesSet()) {
                PaymentMethod method = new PaymentMethod();
                method.setPaymentAmount(
                        reimbursmentEntry.getReimbursedAmount().setScale(2, RoundingMode.HALF_EVEN));
                method.setPaymentDate(payment.getTransactionDate());
                method.setPaymentMechanism(convertToSAFTPaymentMechanism(reimbursmentEntry.getPaymentMethod()));
                payment.getPaymentMethod().add(method);
                payment.setSettlementType(SAFTPTSettlementType.NR);
            }
        } else {
            payment.setSettlementType(SAFTPTSettlementType.NN);
        }

        payment.setSourceID(document.getVersioningCreator());

        // DocumentTotals
        SourceDocuments.Payments.Payment.DocumentTotals docTotals = new SourceDocuments.Payments.Payment.DocumentTotals();

        //Lines
        BigInteger i = BigInteger.ONE;
        for (SettlementEntry settlementEntry : document.getSettlemetEntriesSet()) {
            SourceDocuments.Payments.Payment.Line line = new SourceDocuments.Payments.Payment.Line();
            line.setLineNumber(i);
            //SourceDocument
            SourceDocumentID sourceDocument = new SourceDocumentID();
            sourceDocument.setLineNumber(BigInteger.valueOf(settlementEntry.getInvoiceEntry().getEntryOrder()));
            sourceDocument.setOriginatingON(
                    settlementEntry.getInvoiceEntry().getFinantialDocument().getUiDocumentNumber());
            sourceDocument.setInvoiceDate(convertToXMLDateTime(dataTypeFactory,
                    settlementEntry.getInvoiceEntry().getFinantialDocument().getDocumentDate()));
            sourceDocument.setDescription(settlementEntry.getDescription());
            line.getSourceDocumentID().add(sourceDocument);
            //SettlementAmount
            line.setSettlementAmount(BigDecimal.ZERO);
            if (settlementEntry.getInvoiceEntry().isDebitNoteEntry()) {
                line.setDebitAmount(settlementEntry.getTotalAmount());
            } else if (settlementEntry.getInvoiceEntry().isCreditNoteEntry()) {
                line.setCreditAmount(settlementEntry.getTotalAmount());
            }
            payment.getLine().add(line);
            i = i.add(BigInteger.ONE);
        }
        docTotals.setGrossTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setNetTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setTaxPayable(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_EVEN));
        payment.setDocumentTotals(docTotals);

        // Period
        /*
         * Per?odo contabil?stico (Period) . . . . . . . . . . Deve ser
         * indicado o n?mero do m?s do per?odo de tributa??o, de ?1? a ?12?,
         * contado desde a data do in?cio. Pode ainda ser preenchido com
         * ?13?, ?14?, ?15? ou ?16? para movimentos efectuados no ?ltimo m?s
         * do per?odo de tributa??o, relacionados com o apuramento do
         * resultado. Ex.: movimentos de apuramentos de invent?rios,
         * deprecia??es, ajustamentos ou apuramentos de resultados.
         */
        payment.setPeriod(document.getDocumentDate().getMonthOfYear());

        // SourceID
        /*
         * C?digo do utilizador que registou o movimento (SourceID).
         */
        payment.setSourceID(document.getVersioningCreator());

    } catch (DatatypeConfigurationException e) {

        e.printStackTrace();
    }

    return payment;
}

From source file:ca.ualberta.cmput301w14t08.geochan.adapters.ThreadViewAdapter.java

/**
 * Sets the required fields of the orignal post of the thread.
 * Title, creator, comment, timestamp, location.
 * /*from ww  w.  jav a2s.c o  m*/
 * @param convertView
 *            View container of a listView item.
 */
private void setOPFields(View convertView) {
    // Thread title
    TextView title = (TextView) convertView.findViewById(R.id.thread_view_op_threadTitle);
    // Special case of Viewing a Favourite Comment in ThreadView
    if (thread.getTitle().equals("")) {
        title.setVisibility(View.GONE);
        LinearLayout buttons = (LinearLayout) convertView.findViewById(R.id.thread_view_op_buttons);
        buttons.setVisibility(View.GONE);
    } else {
        title.setText(thread.getTitle());
    }
    // Thread creator
    TextView threadBy = (TextView) convertView.findViewById(R.id.thread_view_op_commentBy);
    threadBy.setText(
            "Posted by " + thread.getBodyComment().getUser() + "#" + thread.getBodyComment().getHash() + "  ");
    if (HashHelper.getHash(thread.getBodyComment().getUser()).equals(thread.getBodyComment().getHash())) {
        threadBy.setBackgroundResource(R.drawable.username_background_thread_rect);
        threadBy.setTextColor(Color.WHITE);
    }

    // Thread body comment
    TextView body = (TextView) convertView.findViewById(R.id.thread_view_op_commentBody);
    body.setText(thread.getBodyComment().getTextPost());
    // Thread timestamp
    TextView threadTime = (TextView) convertView.findViewById(R.id.thread_view_op_commentDate);
    threadTime.setText(thread.getBodyComment().getCommentDateString());
    // Location text
    TextView origPostLocationText = (TextView) convertView.findViewById(R.id.thread_view_op_locationText);
    GeoLocation loc = thread.getBodyComment().getLocation();
    String locDescriptor = loc.getLocationDescription();
    if (loc != null) {
        if (locDescriptor != null) {
            origPostLocationText.setText("near: " + locDescriptor);
        } else {
            // The rounding of long and lat for max 4 decimal digits.
            DecimalFormat format = new DecimalFormat();
            format.setRoundingMode(RoundingMode.HALF_EVEN);
            format.setMinimumFractionDigits(0);
            format.setMaximumFractionDigits(4);

            origPostLocationText.setText("Latitude: " + format.format(loc.getLatitude()) + " Longitude: "
                    + format.format(loc.getLongitude()));
        }
    }

    // Set the thumbnail if there is an image
    if (thread.getBodyComment().hasImage()) {
        ImageButton thumbnail = (ImageButton) convertView.findViewById(R.id.thread_view_comment_thumbnail);
        thumbnail.setVisibility(View.VISIBLE);
        thumbnail.setFocusable(false);
        thumbnail.setImageBitmap(thread.getBodyComment().getImageThumb());
    }
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * {@code n / divisor}.//from  www .  j  av  a 2  s  . co m
 *
 * @param o the object, number or string.
 * @param divisor value by which 'o' is to be divided.
 * @param scale of the {@code n / divisor} quotient to be returned.
 * @param mode {@link java.math.RoundingMode}.
 * @param type return number type.
 * @return {@code (type) (o / divisor)}.
 */
public static <T extends Number> T divide(final Object o, final Number divisor, final Number scale,
        final RoundingMode mode, final Class<T> type) {
    if (type == null)
        return null;
    Number n = valueOf(o);
    if (n == null)
        return setScale(divisor, scale, mode, type);
    if (divisor == null)
        return setScale(n, scale, mode, type);
    MathContext mc = new MathContext(INFINITY_DOUBLE.precision(), RoundingMode.HALF_EVEN);
    if (ClassUtils.isPrimitiveOrWrappers(n, divisor, type))
        mc = MathContext.DECIMAL128;
    if (scale != null)
        return setScale(valueOf(n, BigDecimal.class).divide(valueOf(divisor, BigDecimal.class), mc), scale,
                mode, type);

    return NumberObject.of(type)
            .valueOf(valueOf(n, BigDecimal.class).divide(valueOf(divisor, BigDecimal.class), mc));
}