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:io.bitsquare.gui.util.BSFormatter.java

/**
 * Converts to a fiat with max. 2 decimal places. Last place gets rounded.
 * 0.234 -> 0.23/*from  w  w  w  .  j a  v  a 2 s  .c o m*/
 * 0.235 -> 0.24
 *
 * @param input
 * @return
 */

public Fiat parseToFiatWithPrecision(String input, String currencyCode) {
    if (input != null && input.length() > 0) {
        try {
            return parseToFiat(
                    new BigDecimal(cleanInput(input)).setScale(2, BigDecimal.ROUND_HALF_UP).toString(),
                    currencyCode);
        } catch (Throwable t) {
            log.warn("Exception at parseToFiatWithPrecision: " + t.toString());
            return Fiat.valueOf(currencyCode, 0);
        }

    }
    return Fiat.valueOf(currencyCode, 0);
}

From source file:org.kuali.kfs.fp.document.service.impl.DisbursementVoucherTaxServiceImpl.java

/**
 * This method generates non-resident alien (NRA) tax lines for the given disbursement voucher.  
 * /*from  w  w w .ja  v a  2s .c  o  m*/
 * The NRA tax lines consist of three possible sets of tax lines: 
 * - Gross up tax lines
 * - Federal tax lines
 * - State tax lines
 * 
 * Gross up tax lines are generated if the income tax gross up code is set on the DisbursementVoucherNonResidentAlienTax 
 * attribute of the disbursement voucher.
 * 
 * Federal tax lines are generated if the federal tax rate in the DisbursementVoucherNonResidentAlienTax attribute is
 * other than zero.
 * 
 * State tax lines are generated if the state tax rate in the DisbursementVoucherNonResidentAlienTax attribute is
 * other than zero.
 * 
 * @param document The disbursement voucher the NRA tax lines will be added to.
 * 
 * @see org.kuali.kfs.fp.document.service.DisbursementVoucherTaxService#generateNRATaxLines(org.kuali.kfs.fp.document.DisbursementVoucherDocument)
 */
protected void generateNRATaxLines(DisbursementVoucherDocument document) {
    // retrieve first accounting line for tax line attributes
    AccountingLine line1 = document.getSourceAccountingLine(0);

    List taxLineNumbers = new ArrayList();

    // generate gross up
    if (document.getDvNonResidentAlienTax().isIncomeTaxGrossUpCode()) {
        AccountingLine grossLine = null;
        try {
            grossLine = (SourceAccountingLine) document.getSourceAccountingLineClass().newInstance();
        } catch (IllegalAccessException e) {
            throw new InfrastructureException("unable to access sourceAccountingLineClass", e);
        } catch (InstantiationException e) {
            throw new InfrastructureException("unable to instantiate sourceAccountingLineClass", e);
        }

        grossLine.setDocumentNumber(document.getDocumentNumber());
        grossLine.setSequenceNumber(document.getNextSourceLineNumber());
        grossLine.setChartOfAccountsCode(line1.getChartOfAccountsCode());
        grossLine.setAccountNumber(line1.getAccountNumber());
        grossLine.setFinancialObjectCode(line1.getFinancialObjectCode());

        // calculate gross up amount and set as line amount
        BigDecimal federalTaxPercent = document.getDvNonResidentAlienTax().getFederalIncomeTaxPercent()
                .bigDecimalValue();
        BigDecimal stateTaxPercent = document.getDvNonResidentAlienTax().getStateIncomeTaxPercent()
                .bigDecimalValue();
        BigDecimal documentAmount = document.getDisbVchrCheckTotalAmount().bigDecimalValue();

        KualiDecimal grossAmount1 = new KualiDecimal((documentAmount.multiply(federalTaxPercent).divide(
                new BigDecimal(100).subtract(federalTaxPercent).subtract(stateTaxPercent), 5,
                BigDecimal.ROUND_HALF_UP)));
        KualiDecimal grossAmount2 = new KualiDecimal((documentAmount.multiply(stateTaxPercent).divide(
                new BigDecimal(100).subtract(federalTaxPercent).subtract(stateTaxPercent), 5,
                BigDecimal.ROUND_HALF_UP)));
        grossLine.setAmount(grossAmount1.add(grossAmount2));

        // put line number in line number list, and update next line property in document
        taxLineNumbers.add(grossLine.getSequenceNumber());
        document.setNextSourceLineNumber(new Integer(document.getNextSourceLineNumber().intValue() + 1));

        // add to source accounting lines
        grossLine.refresh();
        document.getSourceAccountingLines().add(grossLine);

        // update check total, is added because line amount is negative, so this will take check amount down
        document.setDisbVchrCheckTotalAmount(document.getDisbVchrCheckTotalAmount().add(grossLine.getAmount()));
    }

    KualiDecimal taxableAmount = document.getDisbVchrCheckTotalAmount();

    // generate federal tax line
    if (!(KualiDecimal.ZERO.equals(document.getDvNonResidentAlienTax().getFederalIncomeTaxPercent()))) {
        String federalTaxChart = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.FEDERAL_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_CHART_SUFFIX);
        String federalTaxAccount = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.FEDERAL_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_ACCOUNT_SUFFIX);
        String federalTaxObjectCode = parameterService.getSubParameterValueAsString(
                DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.FEDERAL_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                document.getDvNonResidentAlienTax().getIncomeClassCode());
        if (StringUtils.isBlank(federalTaxChart) || StringUtils.isBlank(federalTaxAccount)
                || StringUtils.isBlank(federalTaxObjectCode)) {
            LOG.error("Unable to retrieve federal tax parameters.");
            throw new RuntimeException("Unable to retrieve federal tax parameters.");
        }

        AccountingLine federalTaxLine = generateTaxAccountingLine(document, federalTaxChart, federalTaxAccount,
                federalTaxObjectCode, document.getDvNonResidentAlienTax().getFederalIncomeTaxPercent(),
                taxableAmount);

        // put line number in line number list, and update next line property in document
        taxLineNumbers.add(federalTaxLine.getSequenceNumber());
        document.setNextSourceLineNumber(new Integer(document.getNextSourceLineNumber().intValue() + 1));

        // add to source accounting lines
        federalTaxLine.refresh();
        document.getSourceAccountingLines().add(federalTaxLine);

        // update check total, is added because line amount is negative, so this will take check amount down
        document.setDisbVchrCheckTotalAmount(
                document.getDisbVchrCheckTotalAmount().add(federalTaxLine.getAmount()));
    }

    // generate state tax line
    if (!(KualiDecimal.ZERO.equals(document.getDvNonResidentAlienTax().getStateIncomeTaxPercent()))) {
        String stateTaxChart = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.STATE_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_CHART_SUFFIX);
        String stateTaxAccount = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.STATE_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_ACCOUNT_SUFFIX);
        String stateTaxObjectCode = parameterService.getSubParameterValueAsString(
                DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.STATE_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                document.getDvNonResidentAlienTax().getIncomeClassCode());

        if (StringUtils.isBlank(stateTaxChart) || StringUtils.isBlank(stateTaxAccount)
                || StringUtils.isBlank(stateTaxObjectCode)) {
            LOG.error("Unable to retrieve state tax parameters.");
            throw new RuntimeException("Unable to retrieve state tax parameters.");
        }

        AccountingLine stateTaxLine = generateTaxAccountingLine(document, stateTaxChart, stateTaxAccount,
                stateTaxObjectCode, document.getDvNonResidentAlienTax().getStateIncomeTaxPercent(),
                taxableAmount);

        // put line number in line number list, and update next line property in document
        taxLineNumbers.add(stateTaxLine.getSequenceNumber());
        document.setNextSourceLineNumber(new Integer(document.getNextSourceLineNumber().intValue() + 1));

        // add to source accounting lines
        stateTaxLine.refresh();
        document.getSourceAccountingLines().add(stateTaxLine);

        // update check total, is added because line amount is negative, so this will take check amount down
        document.setDisbVchrCheckTotalAmount(
                document.getDisbVchrCheckTotalAmount().add(stateTaxLine.getAmount()));
    }

    // update line number field
    document.getDvNonResidentAlienTax()
            .setFinancialDocumentAccountingLineText(StringUtils.join(taxLineNumbers.iterator(), ","));
}

From source file:com.lloydtorres.stately.helpers.SparkleHelper.java

/**
 * Return a human-readable date string from a UTC timestamp.
 * @param c App context// w w w.jav a  2s. c om
 * @param sec Unix timestamp.
 * @return A human-readable date string (e.g. moments ago, 1 week ago).
 */
public static String getReadableDateFromUTC(Context c, long sec) {
    long curTime = System.currentTimeMillis();
    long inputTime = sec * 1000L;
    long timeDiff = inputTime - curTime;
    long timeDiffAbs = Math.abs(timeDiff);

    // If the time diff is zero or positive, it's in the future; past otherwise
    String pastIndicator = (timeDiff >= 0) ? c.getString(R.string.time_from_now)
            : c.getString(R.string.time_ago);
    String template = c.getString(R.string.time_generic_template);

    if (timeDiffAbs < 60000L) {
        // less than a minute
        template = String.format(Locale.US, c.getString(R.string.time_moments_template),
                c.getString(R.string.time_moments), pastIndicator);
    } else if (timeDiffAbs < 3600000L) {
        // less than an hour
        BigDecimal calc = BigDecimal.valueOf(timeDiffAbs / 60000D);
        int minutes = calc.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        template = String.format(Locale.US, template, minutes,
                English.plural(c.getString(R.string.time_minute), minutes), pastIndicator);
    } else if (timeDiffAbs < 86400000L) {
        // less than a day
        BigDecimal calc = BigDecimal.valueOf(timeDiffAbs / 3600000D);
        int hours = calc.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        template = String.format(Locale.US, template, hours,
                English.plural(c.getString(R.string.time_hour), hours), pastIndicator);
    } else if (timeDiffAbs < 604800000L) {
        // less than a week
        BigDecimal calc = BigDecimal.valueOf(timeDiffAbs / 86400000D);
        int days = calc.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        template = String.format(Locale.US, template, days,
                English.plural(c.getString(R.string.time_day), days), pastIndicator);
    } else {
        template = sdf.format(new Date(inputTime));
    }

    return template;
}

From source file:org.kuali.kfs.module.ar.businessobject.CustomerCreditMemoDetail.java

public void recalculateBasedOnEnteredItemAmount(CustomerCreditMemoDocument customerCreditMemoDocument) {
    BigDecimal invItemUnitPrice = getCustomerInvoiceDetail().getInvoiceItemUnitPrice();
    creditMemoItemQuantity = creditMemoItemTotalAmount.bigDecimalValue().divide(invItemUnitPrice,
            ArConstants.ITEM_QUANTITY_SCALE, BigDecimal.ROUND_HALF_UP);

    if (customerCreditMemoDocument.getArTaxService().isCustomerInvoiceDetailTaxable(
            customerCreditMemoDocument.getInvoice(), getCustomerInvoiceDetail())) {
        creditMemoItemTaxAmount = customerCreditMemoDocument.getTaxService().getTotalSalesTaxAmount(
                customerCreditMemoDocument.getInvoice().getBillingDate(),
                customerCreditMemoDocument.getPostalCode(), creditMemoItemTotalAmount);
    } else {//from w w  w  .  j  ava  2s.  c om
        creditMemoItemTaxAmount = KualiDecimal.ZERO;
    }
    creditMemoLineTotalAmount = creditMemoItemTotalAmount.add(creditMemoItemTaxAmount);
}

From source file:org.openbitcoinwidget.WidgetProvider.java

private static String round(Double value, WidgetPreferences preferences) {
    if (value == null) {
        return "N/A";
    }/*from   www .  j  ava 2 s  . co m*/
    value *= preferences.getCurrencyUnit().scale;

    int decimals;
    if (value >= 10) {
        decimals = 0;
    } else if (value >= 1) {
        decimals = 1;
    } else if (value >= .1) {
        decimals = 2;
    } else if (value >= .01) {
        decimals = 3;
    } else {
        decimals = 4;
    }

    return BigDecimal.valueOf(value).setScale(decimals, BigDecimal.ROUND_HALF_UP).toString();
}

From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java

/**
 * Gives the consolidated collection for the dates and billing service
 *
 * @param fromDate//from w w w. j  ava 2 s  . c o m
 * @param toDate
 * @param billingService
 * @return BigDecimal
 */
public BigDecimal getConsolidatedCollForYears(final Date fromDate, final Date toDate,
        final String billingService) {
    final QueryBuilder queryBuilder = QueryBuilders.boolQuery()
            .must(QueryBuilders.rangeQuery(RECEIPT_DATEINDEX)
                    .gte(WaterTaxConstants.DATEFORMATTER_YYYY_MM_DD.format(fromDate))
                    .lte(WaterTaxConstants.DATEFORMATTER_YYYY_MM_DD.format(toDate)).includeUpper(false))
            .must(QueryBuilders.matchQuery(BILLING_SERVICE, billingService))
            .mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED));
    final SearchQuery searchQueryColl = new NativeSearchQueryBuilder()
            .withIndices(WaterTaxConstants.COLLECTION_INDEX_NAME).withQuery(queryBuilder)
            .addAggregation(AggregationBuilders.sum(COLLECTION_TOTAL).field(TOTAL_AMOUNT)).build();

    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());

    final Sum aggr = collAggr.get(COLLECTION_TOTAL);
    return BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP);
}

From source file:com.epam.parso.impl.CSVDataWriterImpl.java

/**
 * The function to convert a double value into a string. If the text presentation of the double is longer
 * than {@link CSVDataWriterImpl#ROUNDING_LENGTH}, the rounded off value of the double includes
 * the {@link CSVDataWriterImpl#ACCURACY} number of digits from the first non-zero value.
 *
 * @param value the input numeric value to convert.
 * @return the string with the text presentation of the input numeric value.
 *//*from   ww w  . j ava 2s.  c  o m*/
protected static String convertDoubleElementToString(Double value) {
    String valueToPrint = String.valueOf(value);
    if (valueToPrint.length() > ROUNDING_LENGTH) {
        int lengthBeforeDot = (int) Math.ceil(Math.log10(Math.abs(value)));
        BigDecimal bigDecimal = new BigDecimal(value);
        bigDecimal = bigDecimal.setScale(ACCURACY - lengthBeforeDot, BigDecimal.ROUND_HALF_UP);
        valueToPrint = String.valueOf(bigDecimal.doubleValue());
    }
    valueToPrint = trimZerosFromEnd(valueToPrint);
    return valueToPrint;
}

From source file:org.egov.wtms.service.es.WaterChargeElasticSearchService.java

/**
 * Populates the consolidated demand information in CollectionIndexDetails
 *
 * @param waterChargedashBoardRequest/*from w w  w.  j av  a2 s . c om*/
 * @param collectionIndexDetails
 */
public List<WaterChargeDashBoardResponse> getConsolidatedDemandInfo(
        final WaterChargeDashBoardRequest waterChargedashBoardRequest) {
    final List<WaterChargeDashBoardResponse> collectionIndexDetailsList = new ArrayList<>();
    final WaterChargeDashBoardResponse collectionIndexDetails = new WaterChargeDashBoardResponse();

    Date fromDate;
    Date toDate;
    /**
     * For fetching total demand between the date ranges if dates are sent
     * in the request, consider fromDate and toDate+1 , else calculate from
     * current year start date till current date+1 day
     */
    if (StringUtils.isNotBlank(waterChargedashBoardRequest.getFromDate())
            && StringUtils.isNotBlank(waterChargedashBoardRequest.getToDate())) {
        fromDate = DateUtils.getDate(waterChargedashBoardRequest.getFromDate(), "yyyy-MM-dd");
        toDate = org.apache.commons.lang3.time.DateUtils
                .addDays(DateUtils.getDate(waterChargedashBoardRequest.getToDate(), "yyyy-MM-dd"), 1);
    } else {
        fromDate = new DateTime().withMonthOfYear(4).dayOfMonth().withMinimumValue().toDate();
        toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);
    }
    Long startTime = System.currentTimeMillis();
    final BigDecimal totalDemand = getTotalDemandBasedOnInputFilters(waterChargedashBoardRequest);
    Long timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Time taken by getTotalDemandBasedOnInputFilters() is (millisecs) : " + timeTaken);
    startTime = System.currentTimeMillis();
    final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1;
    collectionIndexDetails.setTotalDmd(totalDemand);

    // Proportional Demand = (totalDemand/12)*noOfmonths
    final BigDecimal proportionalDemand = totalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
            .multiply(BigDecimal.valueOf(noOfMonths));
    collectionIndexDetails.setCurrentYearTillDateDmd(proportionalDemand.setScale(0, BigDecimal.ROUND_HALF_UP));

    // performance = (current year tilldate collection * 100)/(proportional
    // demand)
    collectionIndexDetails.setPerformance(
            collectionIndexDetails.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100)
                    .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP));
    // variance = ((currentYearCollection -
    // lastYearCollection)*100)/lastYearCollection
    BigDecimal variation;
    if (collectionIndexDetails.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0)
        variation = WaterTaxConstants.BIGDECIMAL_100;
    else
        variation = collectionIndexDetails.getCurrentYearTillDateColl()
                .subtract(collectionIndexDetails.getLastYearTillDateColl())
                .multiply(WaterTaxConstants.BIGDECIMAL_100)
                .divide(collectionIndexDetails.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP);
    collectionIndexDetails.setLastYearVar(variation);
    timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug(
                "Time taken for setting values in getConsolidatedDemandInfo() is (millisecs) : " + timeTaken);
    final ErrorDetails errorDetails = new ErrorDetails();
    errorDetails.setErrorCode(WaterTaxConstants.THIRD_PARTY_ERR_CODE_SUCCESS);
    errorDetails.setErrorMessage(WaterTaxConstants.THIRD_PARTY_ERR_MSG_SUCCESS);
    collectionIndexDetails.setErrorDetails(errorDetails);
    collectionIndexDetailsList.add(collectionIndexDetails);
    return collectionIndexDetailsList;
}

From source file:org.egov.collection.service.elasticsearch.CollectionDocumentElasticSearchService.java

/**
 * Gives the consolidated collection for the dates and billing service
 *
 * @param fromDate//from   w w  w .j  a v a 2s.  c om
 * @param toDate
 * @param serviceDetails
 * @return BigDecimal
 */
public BigDecimal getConsolidatedCollForYears(final Date fromDate, final Date toDate,
        final List<String> serviceDetails) {
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
            .must(QueryBuilders.rangeQuery(RECEIPT_DATE).gte(DATEFORMATTER_YYYY_MM_DD.format(fromDate))
                    .lte(DATEFORMATTER_YYYY_MM_DD.format(toDate)).includeUpper(false))
            .mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED));
    if (!serviceDetails.isEmpty())
        boolQuery = boolQuery.must(QueryBuilders.termsQuery(BILLING_SERVICE, serviceDetails));
    final SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(COLLECTION_INDEX_NAME)
            .withQuery(boolQuery).addAggregation(AggregationBuilders.sum(COLLECTIONTOTAL).field(TOTAL_AMOUNT))
            .build();

    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());

    final Sum aggr = collAggr.get(COLLECTIONTOTAL);
    return BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP);
}

From source file:com.github.totyumengr.minicubes.core.MiniCubeTest.java

@Test
public void test_2_3_Zero_BigDecimail() throws Throwable {

    BigDecimal zero = new BigDecimal(0).setScale(8, BigDecimal.ROUND_HALF_UP);
    System.out.println(zero);//from   ww  w  . j  ava  2  s  . c  om
}