Example usage for java.math MathContext MathContext

List of usage examples for java.math MathContext MathContext

Introduction

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

Prototype

public MathContext(int setPrecision, RoundingMode setRoundingMode) 

Source Link

Document

Constructs a new MathContext with a specified precision and rounding mode.

Usage

From source file:org.libreplan.business.orders.daos.OrderElementDAO.java

private BigDecimal average(BigDecimal divisor, BigDecimal sum) {
    BigDecimal average = new BigDecimal(0);
    if (sum.compareTo(new BigDecimal(0)) > 0) {
        average = sum.divide(divisor, new MathContext(2, RoundingMode.HALF_UP));
    }/* w  ww  .  jav a 2 s  .c  om*/
    return average;
}

From source file:com.globocom.grou.report.ts.opentsdb.OpenTSDBClient.java

private double formatValue(double value) {
    try {/*ww  w  .  j  a  v  a 2 s. c o  m*/
        return BigDecimal.valueOf(value).round(new MathContext(4, RoundingMode.HALF_UP)).doubleValue();
    } catch (NumberFormatException ignore) {
        return BigDecimal.valueOf(0d).round(new MathContext(4, RoundingMode.HALF_UP)).doubleValue();
    }
}

From source file:net.mikaboshi.intra_mart.tools.log_stats.formatter.TemplateFileReportFormatter.java

/**
 * ??URL??N?//  www.jav  a 2s .  c  o m
 * @param report
 * @param rootMap
 */
private void setRequestUrlRank(Report report, Map<String, Object> rootMap) {

    Map<String, Object> requestUrlRank = new HashMap<String, Object>();
    rootMap.put("requestUrlRank", requestUrlRank);

    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    requestUrlRank.put("list", list);

    List<RequestUrlReportEntry> reportList = report.getRequestUrlReportList();

    requestUrlRank.put("size", report.getParameter().getRequestUrlRankSize());
    requestUrlRank.put("total", reportList.size());

    MathContext percentMathContext = new MathContext(2, RoundingMode.HALF_UP);

    int i = 0;

    for (RequestUrlReportEntry entry : reportList) {

        if (++i > report.getParameter().getRequestUrlRankSize()) {
            break;
        }

        Map<String, Object> row = new HashMap<String, Object>();
        list.add(row);

        row.put("url", entry.url);
        row.put("count", entry.count);
        row.put("pageTimeSum", entry.pageTimeSum);
        row.put("pageTimeAverage", entry.pageTimeAverage);
        row.put("pageTimeMin", entry.pageTimeMin);
        row.put("pageTimeMedian", entry.pageTimeMedian);
        row.put("pageTime90Percent", entry.pageTime90Percent);
        row.put("pageTimeMax", entry.pageTimeMax);
        row.put("pageTimeStandardDeviation", entry.pageTimeStandardDeviation);
        row.put("countRate", new BigDecimal(entry.countRate * 100, percentMathContext).doubleValue());
        row.put("pageTimeRate", new BigDecimal(entry.pageTimeRate * 100, percentMathContext).doubleValue());

        if (reportParameter.isJsspPath()) {
            row.put("jsspPath", getJsspPath(entry.url));
        }
    }
}

From source file:net.mikaboshi.intra_mart.tools.log_stats.formatter.TemplateFileReportFormatter.java

/**
 * ????N?/*from  w w  w  .ja v  a  2s.c  om*/
 * @param report
 * @param rootMap
 */
private void setSessionRank(Report report, Map<String, Object> rootMap) {

    Map<String, Object> sessionRank = new HashMap<String, Object>();
    rootMap.put("sessionRank", sessionRank);

    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    sessionRank.put("list", list);

    List<SessionReportEntry> reportList = report.getSessionReportList();

    sessionRank.put("size", report.getParameter().getSessionRankSize());
    sessionRank.put("total", reportList.size());

    MathContext percentMathContext = new MathContext(2, RoundingMode.HALF_UP);

    int i = 0;

    for (SessionReportEntry entry : reportList) {

        if (++i > report.getParameter().getSessionRankSize()) {
            break;
        }

        Map<String, Object> row = new HashMap<String, Object>();
        list.add(row);

        row.put("sessionId", entry.sessionId);
        row.put("userId", report.getUserIdFromSessionId(entry.sessionId, ""));
        row.put("count", entry.count);
        row.put("pageTimeSum", entry.pageTimeSum);
        row.put("pageTimeAverage", entry.pageTimeAverage);
        row.put("pageTimeMin", entry.pageTimeMin);
        row.put("pageTimeMedian", entry.pageTimeMedian);
        row.put("pageTime90Percent", entry.pageTime90Percent);
        row.put("pageTimeMax", entry.pageTimeMax);
        row.put("pageTimeStandardDeviation", entry.pageTimeStandardDeviation);
        row.put("countRate", new BigDecimal(entry.countRate * 100, percentMathContext).doubleValue());
        row.put("pageTimeRate", new BigDecimal(entry.pageTimeRate * 100, percentMathContext).doubleValue());
        row.put("firstAccessTime", entry.firstAccessTime);
        row.put("lastAccessTime", entry.lastAccessTime);
    }
}

From source file:org.gradoop.flink.model.impl.operators.aggregation.AggregationTest.java

@Test
public void testWithMixedTypePropertyValues() throws Exception {
    FlinkAsciiGraphLoader loader = getLoaderFromString(
            "g0[" + "(va {vp=0.5});" + "(vc {vp=1});" + "(va)-[ea {ep=2L}]->(vb);" + "(vb)-[eb {ep=2.0F}]->(vc)"
                    + "]" + "g1[" + "(va)-[ea]->(vb);" + "]" + "g2[]");

    GraphCollection inputCollection = loader.getGraphCollectionByVariables("g0", "g1", "g2");

    SumVertexProperty sumVertexProperty = new SumVertexProperty(VERTEX_PROPERTY);

    SumEdgeProperty sumEdgeProperty = new SumEdgeProperty(EDGE_PROPERTY);

    GraphCollection outputCollection = inputCollection.apply(new ApplyAggregation(sumVertexProperty))
            .apply(new ApplyAggregation(sumEdgeProperty));

    GradoopId g0Id = loader.getGraphHeadByVariable("g0").getId();
    GradoopId g1Id = loader.getGraphHeadByVariable("g1").getId();
    GradoopId g2Id = loader.getGraphHeadByVariable("g2").getId();

    List<GraphHead> graphHeads = outputCollection.getGraphHeads().collect();

    for (EPGMGraphHead graphHead : graphHeads) {
        assertTrue("edge sum not set", graphHead.hasProperty(sumEdgeProperty.getAggregatePropertyKey()));
        assertTrue("vertex sum not set", graphHead.hasProperty(sumVertexProperty.getAggregatePropertyKey()));

        PropertyValue vertexAggregate = graphHead.getPropertyValue(sumVertexProperty.getAggregatePropertyKey());

        PropertyValue edgeAggregate = graphHead.getPropertyValue(sumEdgeProperty.getAggregatePropertyKey());

        if (graphHead.getId().equals(g0Id)) {
            assertEquals(1.5d, vertexAggregate.getDouble(), 0.00001);
            assertEquals(new BigDecimal("4.0"),
                    edgeAggregate.getBigDecimal().round(new MathContext(2, RoundingMode.HALF_UP)));
        } else if (graphHead.getId().equals(g1Id)) {
            assertEquals(0.5f, vertexAggregate.getFloat(), 0.00001);
            assertEquals(2L, edgeAggregate.getLong());
        } else if (graphHead.getId().equals(g2Id)) {
            assertEquals(PropertyValue.NULL_VALUE, vertexAggregate);
            assertEquals(PropertyValue.NULL_VALUE, edgeAggregate);
        }//ww w.j  a v  a  2 s  .co  m
    }
}

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

@Transactional
@Override/*from w  ww . jav a  2s .  c  om*/
public CommandProcessingResult calculateInterest(final Long savingsId) {

    final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId);
    checkClientOrGroupActive(account);

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

    account.calculateInterestUsing(mc, today);

    this.savingAccountRepository.save(account);

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

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  w  w  . j  av a 2s.c o m*/
    this.savingAccountRepository.save(account);

    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);
}

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);
    }/*w ww. java 2 s. co 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  ava2  s  .  c  o  m

    return percentageOf;
}

From source file:com.gst.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from   w  w w  . j a va 2 s  . c  o  m*/
public CommandProcessingResult calculateInterest(final Long savingsId) {

    final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService
            .isSavingsInterestPostingAtCurrentPeriodEnd();
    final Integer financialYearBeginningMonth = this.configurationDomainService
            .retrieveFinancialYearBeginningMonth();

    final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId);
    checkClientOrGroupActive(account);
    final LocalDate today = DateUtils.getLocalDateOfTenant();
    final MathContext mc = new MathContext(15, MoneyHelper.getRoundingMode());
    boolean isInterestTransfer = false;
    final LocalDate postInterestOnDate = null;
    account.calculateInterestUsing(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd,
            financialYearBeginningMonth, postInterestOnDate);

    this.savingAccountRepositoryWrapper.save(account);

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