Example usage for java.math BigDecimal ROUND_HALF_DOWN

List of usage examples for java.math BigDecimal ROUND_HALF_DOWN

Introduction

In this page you can find the example usage for java.math BigDecimal ROUND_HALF_DOWN.

Prototype

int ROUND_HALF_DOWN

To view the source code for java.math BigDecimal ROUND_HALF_DOWN.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.

Usage

From source file:com.example.aaron.test.MyGLSurfaceView.java

private static BigDecimal truncateDecimal(float x, int numberofDecimals) {
    if (x > 0) {
        return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_HALF_UP);
    } else {/*from w  w w .j  a  v a 2 s .c  o  m*/
        return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_HALF_DOWN);
    }
}

From source file:org.globus.exec.client.HackedGramJob.java

private EndpointReferenceType createJobEndpoint(final ManagedJobFactoryPortType factoryPort,
        final boolean batch) throws Exception {
    // Create a service instance base on creation info
    logger.debug("creating ManagedJob instance");

    if (logger.isDebugEnabled()) {
        long millis = System.currentTimeMillis();
        BigDecimal seconds = new BigDecimal(((double) millis) / 1000);
        seconds = seconds.setScale(3, BigDecimal.ROUND_HALF_DOWN);
        logger.debug("submission time, in seconds from the Epoch:" + "\nbefore: " + seconds.toString());
        logger.debug("\nbefore, in milliseconds: " + millis);
    }//from ww  w  .  j a  va2  s . c  o m

    ((org.apache.axis.client.Stub) factoryPort).setTimeout(this.axisStubTimeOut);

    CreateManagedJobInputType jobInput = new CreateManagedJobInputType();
    jobInput.setInitialTerminationTime(getTerminationTime());
    if (this.id != null) {
        jobInput.setJobID(new AttributedURI(this.id));
    }
    if (this.jobDescription instanceof MultiJobDescriptionType) {
        jobInput.setMultiJob((MultiJobDescriptionType) this.getDescription());
    } else {
        jobInput.setJob(this.getDescription());
    }

    if (!batch) {
        if (this.useDefaultNotificationConsumer) {
            setupNotificationConsumerManager();
        }

        try {
            if (this.useDefaultNotificationConsumer) {
                setupNotificationConsumer();
            }

            Subscribe subscriptionRequest = new Subscribe();
            subscriptionRequest.setConsumerReference(this.notificationConsumerEPR);
            TopicExpressionType topicExpression = new TopicExpressionType(WSNConstants.SIMPLE_TOPIC_DIALECT,
                    ManagedJobConstants.RP_STATE);
            subscriptionRequest.setTopicExpression(topicExpression);
            jobInput.setSubscribe(subscriptionRequest);
        } catch (Exception e) {
            // may happen...? Let's not fail.
            logger.error(e);
            try {
                unbind();
            } catch (Exception unbindEx) {
                // let's not fail the unbinding
                logger.error(unbindEx);
            }
        }
    }

    if (logger.isInfoEnabled()) {
        logger.info("<startTime name=\"createManagedJob\">" + System.currentTimeMillis() + "</startTime>");
    }
    CreateManagedJobOutputType response = factoryPort.createManagedJob(jobInput);
    if (logger.isInfoEnabled()) {
        logger.info("<endTime name=\"createManagedJob\">" + System.currentTimeMillis() + "</endTime");
    }
    EndpointReferenceType jobEPR = (EndpointReferenceType) ObjectSerializer
            .clone(response.getManagedJobEndpoint());

    // This doesn't work with GRAM.NET for some reason...
    /*
    if(logger.isDebugEnabled()) {
       * logger.debug("Job Handle: " + AuditUtil.eprToGridId(jobEPR)); Element jobEndpointElement = null; try { jobEndpointElement = ObjectSerializer.toElement( jobEPR, new QName( "http://schemas.xmlsoap.org/ws/2004/03/addressing", "EndpointReferenceType")); } catch (Exception e)
       * { throw new RuntimeException(e); } logger.debug("Job EPR: " + XmlUtils.toString(jobEndpointElement));
    }
       */

    EndpointReferenceType subscriptionEPR = response.getSubscriptionEndpoint();

    if (subscriptionEPR != null) {
        this.notificationProducerEPR = (EndpointReferenceType) ObjectSerializer.clone(subscriptionEPR);
    }

    if (logger.isDebugEnabled()) {
        Calendar terminationTime = response.getNewTerminationTime();
        Calendar serviceCurrentTime = response.getCurrentTime();
        logger.debug(
                "Termination time granted by the factory to the job resource: " + terminationTime.getTime());
        logger.debug("Current time seen by the factory service on creation: " + serviceCurrentTime.getTime());
    }

    return jobEPR;
}

From source file:org.jumpmind.symmetric.statistic.AbstractStatsByPeriodMap.java

protected int round(int value) {
    return 5 * new BigDecimal((double) value / 5d).setScale(2, BigDecimal.ROUND_HALF_DOWN).intValue();
}

From source file:org.kuali.kfs.module.ar.document.service.impl.ContractsGrantsInvoiceDocumentServiceImpl.java

/**
 * @see org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService#prorateBill(org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument)
 *//*from w w  w .j  av a  2  s. c om*/
@Override
public void prorateBill(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument)
        throws WorkflowException {
    KualiDecimal totalCost = new KualiDecimal(0); // Amount to be billed on this invoice
    // must iterate through the invoice details because the user might have manually changed the value
    for (ContractsGrantsInvoiceDetail invD : contractsGrantsInvoiceDocument.getInvoiceDetails()) {
        totalCost = totalCost.add(invD.getInvoiceAmount());
    }
    KualiDecimal billedTotalCost = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail()
            .getTotalPreviouslyBilled(); // Total Billed so far
    KualiDecimal accountAwardTotal = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getAwardTotal(); // AwardTotal

    if (accountAwardTotal.subtract(billedTotalCost).isGreaterEqual(new KualiDecimal(0))) {
        KualiDecimal amountEligibleForBilling = accountAwardTotal.subtract(billedTotalCost);
        // only recalculate if the current invoice is over what's billable.

        if (totalCost.isGreaterThan(amountEligibleForBilling)) {
            // use BigDecimal because percentage should not have only a scale of 2, we need more for accuracy
            BigDecimal percentage = amountEligibleForBilling.bigDecimalValue()
                    .divide(totalCost.bigDecimalValue(), 10, BigDecimal.ROUND_HALF_DOWN);
            KualiDecimal amountToBill = new KualiDecimal(0); // use to check if rounding has left a few cents off

            ContractsGrantsInvoiceDetail largestCostCategory = null;
            BigDecimal largestAmount = BigDecimal.ZERO;
            for (ContractsGrantsInvoiceDetail invD : contractsGrantsInvoiceDocument.getInvoiceDetails()) {
                BigDecimal newValue = invD.getInvoiceAmount().bigDecimalValue().multiply(percentage);
                KualiDecimal newKualiDecimalValue = new KualiDecimal(
                        newValue.setScale(2, BigDecimal.ROUND_DOWN));
                invD.setInvoiceAmount(newKualiDecimalValue);
                amountToBill = amountToBill.add(newKualiDecimalValue);
                if (newValue.compareTo(largestAmount) > 0) {
                    largestAmount = newKualiDecimalValue.bigDecimalValue();
                    largestCostCategory = invD;
                }
            }
            if (!amountToBill.equals(amountEligibleForBilling)) {
                KualiDecimal remaining = amountEligibleForBilling.subtract(amountToBill);
                if (ObjectUtils.isNull(largestCostCategory)
                        && CollectionUtils.isNotEmpty(contractsGrantsInvoiceDocument.getInvoiceDetails())) {
                    largestCostCategory = contractsGrantsInvoiceDocument.getInvoiceDetails().get(0);
                }
                if (ObjectUtils.isNotNull(largestCostCategory)) {
                    largestCostCategory.setInvoiceAmount(largestCostCategory.getInvoiceAmount().add(remaining));
                }
            }
            recalculateTotalAmountBilledToDate(contractsGrantsInvoiceDocument);
        }
    }
}

From source file:org.kuali.kfs.module.ar.document.service.impl.ContractsGrantsInvoiceDocumentServiceImpl.java

/**
 * This method recalculates the invoiceDetailAccountObjectCode in one category that sits behind the scenes of the invoice document.
 * @param contractsGrantsInvoiceDocument
 * @param invoiceDetail/*from  w w w.j a v a2  s .  c o m*/
 * @param total is the sum of the current expenditures from all the object codes in that category
 * @param invoiceDetailAccountObjectCodes
 */
protected void recalculateObjectCodeByCategory(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument,
        ContractsGrantsInvoiceDetail invoiceDetail, KualiDecimal total,
        List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes) {
    KualiDecimal currentExpenditure = invoiceDetail.getInvoiceAmount();
    KualiDecimal newTotalAmount = KualiDecimal.ZERO;

    // if the sum of the object codes is 0, then distribute the expenditure change evenly to all object codes in the category
    if (total.compareTo(KualiDecimal.ZERO) == 0) {
        if (invoiceDetailAccountObjectCodes != null) {
            int numberOfObjectCodes = invoiceDetailAccountObjectCodes.size();
            if (numberOfObjectCodes != 0) {
                KualiDecimal newAmount = new KualiDecimal(currentExpenditure.bigDecimalValue()
                        .divide(new BigDecimal(numberOfObjectCodes), 10, BigDecimal.ROUND_HALF_DOWN));
                for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectCodes) {
                    invoiceDetailAccountObjectCode.setCurrentExpenditures(newAmount);
                    newTotalAmount = newTotalAmount.add(newAmount);
                }
            }
        } else { // if the list is null, then there are no account/object code in the gl_balance_t. So assign the amount to the first object code in the category
            assignCurrentExpenditureToNonExistingAccountObjectCode(contractsGrantsInvoiceDocument,
                    invoiceDetail);
        }
    } else {

        for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectCodes) {
            // this may rarely happen
            // if the initial total is 0, that means none of the object codes in this category is set to bill. If this amount is changed, then just divide evenly among all object codes.
            KualiDecimal newAmount = (new KualiDecimal(invoiceDetailAccountObjectCode.getCurrentExpenditures()
                    .bigDecimalValue().divide(total.bigDecimalValue(), 10, BigDecimal.ROUND_HALF_DOWN)
                    .multiply(currentExpenditure.bigDecimalValue())));
            invoiceDetailAccountObjectCode.setCurrentExpenditures(newAmount);
            newTotalAmount = newTotalAmount.add(newAmount);
        }

        int remainderFromRounding = currentExpenditure.subtract(newTotalAmount).multiply(new KualiDecimal(100))
                .intValue();

        // add remainder from rounding
        KualiDecimal addAmount = new KualiDecimal(0.01);
        if (remainderFromRounding < 0) {
            addAmount = new KualiDecimal(-0.01);
            remainderFromRounding = Math.abs(remainderFromRounding);
        }

        for (int i = 0, j = 0; i < remainderFromRounding; i++, j++) {
            // reset j if its more than size of list
            if (j >= invoiceDetailAccountObjectCodes.size()) {
                j = 0;
            }
            invoiceDetailAccountObjectCodes.get(j).setCurrentExpenditures(
                    invoiceDetailAccountObjectCodes.get(j).getCurrentExpenditures().add(addAmount));
        }
    }
}

From source file:org.kuali.kpme.tklm.time.rules.overtime.weekly.service.WeeklyOvertimeRuleServiceImpl.java

/**
 * Applies overtime subtractions on the indicated TimeBlock.
 *
 * @param timeBlock The time block to reset the overtime on.
 * @param overtimeEarnCode The overtime earn code to apply overtime to.
 * @param convertFromEarnCodes The other earn codes on the time block.
 * @param overtimeHours The overtime hours to apply.
 *
 * @return the amount of overtime hours remaining to be applied.
 *///from   w  w  w  .j  a  v  a 2s. c o m
protected BigDecimal applyNegativeOvertimeOnTimeBlock(TimeBlockBo timeBlock, String overtimeEarnCode,
        Set<String> convertFromEarnCodes, BigDecimal overtimeHours) {
    BigDecimal applied = BigDecimal.ZERO;
    List<TimeHourDetailBo> timeHourDetails = timeBlock.getTimeHourDetails();
    List<TimeHourDetailBo> newTimeHourDetails = new ArrayList<TimeHourDetailBo>();

    for (TimeHourDetailBo timeHourDetail : timeHourDetails) {
        if (convertFromEarnCodes.contains(timeHourDetail.getEarnCode())) {
            TimeHourDetailBo overtimeTimeHourDetail = getTimeHourDetailByEarnCode(timeHourDetails,
                    Collections.singletonList(overtimeEarnCode));

            if (overtimeTimeHourDetail != null) { //if overtime already exists
                TimeHourDetail.Builder overtimeTimeHourDetailBuilder = TimeHourDetail.Builder
                        .create(overtimeTimeHourDetail);
                applied = overtimeTimeHourDetail.getHours().add(overtimeHours, HrConstants.MATH_CONTEXT); // add the negative number of hours of overtime to the existing OT hours
                if (applied.compareTo(BigDecimal.ZERO) >= 0) { //if the OT hours is still greater than or equal to zero, set 'applied' to this new negative number
                    applied = overtimeHours;
                } else {
                    //new OT value is now less than zero
                    applied = overtimeTimeHourDetail.getHours().negate(); //OT is now less than zer
                }

                EarnCodeContract earnCodeObj = HrServiceLocator.getEarnCodeService()
                        .getEarnCode(overtimeEarnCode, timeBlock.getEndDateTime().toLocalDate());
                BigDecimal hours = earnCodeObj.getInflateFactor().multiply(applied, HrConstants.MATH_CONTEXT)
                        .setScale(HrConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_HALF_DOWN);

                overtimeTimeHourDetailBuilder
                        .setHours(overtimeTimeHourDetail.getHours().add(hours, HrConstants.MATH_CONTEXT));

                timeHourDetail.setHours(timeHourDetail.getHours().subtract(applied, HrConstants.MATH_CONTEXT)
                        .setScale(HrConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_HALF_UP));
            }
        }
        newTimeHourDetails.add(timeHourDetail);
    }
    return overtimeHours.subtract(applied);
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private void setSubcontracts(AwardSpecialItems awardSpecialItem) {
    List<AwardApprovedSubaward> awardApprovedSubawards = award.getAwardApprovedSubawards();
    for (AwardApprovedSubaward awardApprovedSubcontractBean : awardApprovedSubawards) {
        Subcontract subcontractType = awardSpecialItem.addNewSubcontract();
        BigDecimal bdecAmount = awardApprovedSubcontractBean.getAmount().bigDecimalValue();
        subcontractType.setAmount(bdecAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN));
        subcontractType.setAwardNumber(awardApprovedSubcontractBean.getAwardNumber());
        subcontractType.setSequenceNumber(awardApprovedSubcontractBean.getSequenceNumber());
        subcontractType.setSubcontractorName(awardApprovedSubcontractBean.getOrganizationName());
    }/*from  w w w  .j av a  2s.  c o m*/
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getPercentageEffort(AwardPerson awardPerson) {
    BigDecimal percentageEffort = null;
    if (awardPerson.getTotalEffort() != null) {
        BigDecimal bdecAmount = new BigDecimal(awardPerson.getTotalEffort().doubleValue());
        percentageEffort = bdecAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }//from w  ww.ja  v  a2 s .  c o  m
    return percentageEffort;
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getAnticipatedTotalIndirect() {
    BigDecimal anticipatedTotalIndirect = null;
    if (awardAmountInfo.getAnticipatedTotalIndirect() != null) {
        BigDecimal bdecAnticipatedTotalIndirect = new BigDecimal(
                awardAmountInfo.getAnticipatedTotalIndirect().doubleValue());
        anticipatedTotalIndirect = bdecAnticipatedTotalIndirect.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }/*from   w w w.j  a  v  a2  s .  c o m*/
    return anticipatedTotalIndirect;
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getAnticipatedTotalDirect() {
    BigDecimal anticipatedTotalDirect = null;
    if (awardAmountInfo.getAnticipatedTotalDirect() != null) {
        anticipatedTotalDirect = new BigDecimal(awardAmountInfo.getAnticipatedTotalDirect().doubleValue());
        anticipatedTotalDirect = anticipatedTotalDirect.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }/*from  w w  w  .j ava 2 s  .c om*/
    return anticipatedTotalDirect;
}