List of usage examples for java.math MathContext MathContext
public MathContext(int setPrecision, RoundingMode setRoundingMode)
From source file:org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java
@Transactional @Override//from ww w .jav a 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; account.calculateInterestUsing(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); this.savingAccountRepository.save(account); return new CommandProcessingResultBuilder() // .withEntityId(savingsId) // .withOfficeId(account.officeId()) // .withClientId(account.clientId()) // .withGroupId(account.groupId()) // .withSavingsId(savingsId) // .build(); }
From source file:com.gst.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, MoneyHelper.getRoundingMode()); final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc); percentageOf = value.multiply(multiplicand, mc); }/* w w w . j a v a 2s. co m*/ return percentageOf; }
From source file:org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java
@Transactional @Override//from w w w . j a v a 2 s. co m public void postInterest(final SavingsAccount account) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService .retrieveFinancialYearBeginningMonth(); if (account.getNominalAnnualInterestRate().compareTo(BigDecimal.ZERO) > 0 || (account.allowOverdraft() && account.getNominalAnnualInterestRateOverdraft().compareTo(BigDecimal.ZERO) > 0)) { final Set<Long> existingTransactionIds = new HashSet<>(); final Set<Long> existingReversedTransactionIds = new HashSet<>(); updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); final LocalDate today = DateUtils.getLocalDateOfTenant(); final MathContext mc = new MathContext(10, MoneyHelper.getRoundingMode()); boolean isInterestTransfer = false; account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); // for generating transaction id's List<SavingsAccountTransaction> transactions = account.getTransactions(); for (SavingsAccountTransaction accountTransaction : transactions) { if (accountTransaction.getId() == null) { this.savingsAccountTransactionRepository.save(accountTransaction); } } this.savingAccountRepository.save(account); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds); } }
From source file:jp.furplag.util.commons.NumberUtils.java
/** * {@code n / divisor}./* ww w.java 2s.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)); }
From source file:org.mifosplatform.portfolio.loanaccount.domain.LoanCharge.java
public static 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); }/*w ww . j a va 2 s.c o m*/ return percentageOf; }
From source file:org.mifosplatform.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java
@Override public CommandProcessingResult adjustSavingsTransaction(final Long savingsId, final Long transactionId, final JsonCommand command) { final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository .findOneByIdAndSavingsAccountId(transactionId, savingsId); if (savingsAccountTransaction == null) { throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId); }//from w w w.j a va 2 s . c o m if (!(savingsAccountTransaction.isDeposit() || savingsAccountTransaction.isWithdrawal()) || savingsAccountTransaction.isReversed()) { throw new TransactionUpdateNotAllowedException(savingsId, transactionId); } if (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); } this.savingsAccountTransactionDataValidator.validate(command); final LocalDate today = DateUtils.getLocalDateOfTenant(); final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId); if (account.isNotActive()) { throwValidationForActiveStatus(SavingsApiConstants.adjustTransactionAction); } final Set<Long> existingTransactionIds = new HashSet<Long>(); final Set<Long> existingReversedTransactionIds = new HashSet<Long>(); updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final LocalDate transactionDate = command .localDateValueOfParameterNamed(SavingsApiConstants.transactionDateParamName); final BigDecimal transactionAmount = command .bigDecimalValueOfParameterNamed(SavingsApiConstants.transactionAmountParamName); final Map<String, Object> changes = new LinkedHashMap<String, Object>(); final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService .createAndPersistPaymentDetail(command, changes); final MathContext mc = new MathContext(10, RoundingMode.HALF_EVEN); account.undoTransaction(transactionId); // for undo withdrawal fee final SavingsAccountTransaction nextSavingsAccountTransaction = this.savingsAccountTransactionRepository .findOneByIdAndSavingsAccountId(transactionId + 1, savingsId); if (nextSavingsAccountTransaction != null && nextSavingsAccountTransaction.isWithdrawalFeeAndNotReversed()) { account.undoTransaction(transactionId + 1); } SavingsAccountTransaction transaction = null; if (savingsAccountTransaction.isDeposit()) { final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, paymentDetail); transaction = account.deposit(transactionDTO); } else { final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, paymentDetail); transaction = account.withdraw(transactionDTO, true); } final Long newtransactionId = saveTransactionToGenerateTransactionId(transaction); if (account.isBeforeLastPostingPeriod(transactionDate) || account.isBeforeLastPostingPeriod(savingsAccountTransaction.transactionLocalDate())) { account.postInterest(mc, today); } else { account.calculateInterestUsing(mc, today); } account.validateAccountBalanceDoesNotBecomeNegative(SavingsApiConstants.adjustTransactionAction); account.activateAccountBasedOnBalance(); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds); return new CommandProcessingResultBuilder() // .withEntityId(newtransactionId) // .withOfficeId(account.officeId()) // .withClientId(account.clientId()) // .withGroupId(account.groupId()) // .withSavingsId(savingsId) // .with(changes)// .build(); }
From source file:org.voltdb.regressionsuites.RegressionSuite.java
protected static final BigDecimal roundDecimalValue(String decimalValueString, boolean roundingEnabled, RoundingMode mode) {/* ww w . j a va 2 s . c om*/ BigDecimal bd = new BigDecimal(decimalValueString); if (!roundingEnabled) { return bd; } int precision = bd.precision(); int scale = bd.scale(); int lostScale = scale - m_defaultScale; if (lostScale <= 0) { return bd; } int newPrecision = precision - lostScale; MathContext mc = new MathContext(newPrecision, mode); BigDecimal nbd = bd.round(mc); assertTrue(nbd.scale() <= m_defaultScale); if (nbd.scale() != m_defaultScale) { nbd = nbd.setScale(m_defaultScale); } assertEquals(getRoundingString("Decimal Scale setting failure"), m_defaultScale, nbd.scale()); return nbd; }
From source file:org.apache.fineract.portfolio.loanaccount.domain.LoanCharge.java
public static BigDecimal percentageOf(final BigDecimal value, final BigDecimal percentage) { BigDecimal percentageOf = BigDecimal.ZERO; if (isGreaterThanZero(value)) { final MathContext mc = new MathContext(8, MoneyHelper.getRoundingMode()); final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc); percentageOf = value.multiply(multiplicand, mc); }//w w w . j a va2 s . com return percentageOf; }
From source file:com.gst.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java
@Transactional @Override/*from w w w . j av a 2 s. co m*/ public void postInterest(final SavingsAccount account, final boolean postInterestAs, final LocalDate transactionDate) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService .retrieveFinancialYearBeginningMonth(); if (account.getNominalAnnualInterestRate().compareTo(BigDecimal.ZERO) > 0 || (account.allowOverdraft() && account.getNominalAnnualInterestRateOverdraft().compareTo(BigDecimal.ZERO) > 0)) { final Set<Long> existingTransactionIds = new HashSet<>(); final Set<Long> existingReversedTransactionIds = new HashSet<>(); updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); final LocalDate today = DateUtils.getLocalDateOfTenant(); final MathContext mc = new MathContext(10, MoneyHelper.getRoundingMode()); boolean isInterestTransfer = false; LocalDate postInterestOnDate = null; if (postInterestAs) { postInterestOnDate = transactionDate; } account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postInterestOnDate); // for generating transaction id's List<SavingsAccountTransaction> transactions = account.getTransactions(); for (SavingsAccountTransaction accountTransaction : transactions) { if (accountTransaction.getId() == null) { this.savingsAccountTransactionRepository.save(accountTransaction); } } this.savingAccountRepositoryWrapper.saveAndFlush(account); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds); } }
From source file:module.workingCapital.presentationTier.action.WorkingCapitalAction.java
private ActionForward exportInfoToExcel(Set<WorkingCapitalProcess> processes, WorkingCapitalContext context, HttpServletResponse response) throws Exception { final Integer year = context.getWorkingCapitalYear().getYear(); SheetData<WorkingCapitalProcess> sheetData = new SheetData<WorkingCapitalProcess>(processes) { @Override// w ww.j av a 2s . c om protected void makeLine(WorkingCapitalProcess workingCapitalProcess) { if (workingCapitalProcess == null) { return; } final WorkingCapital workingCapital = workingCapitalProcess.getWorkingCapital(); final WorkingCapitalInitialization initialization = workingCapital .getWorkingCapitalInitialization(); final AccountingUnit accountingUnit = workingCapital.getAccountingUnit(); addCell(getLocalizedMessate("label.module.workingCapital.year"), year); addCell(getLocalizedMessate("label.module.workingCapital"), workingCapitalProcess.getWorkingCapital().getUnit().getPresentationName()); addCell(getLocalizedMessate("WorkingCapitalProcessState"), workingCapitalProcess.getPresentableAcquisitionProcessState().getLocalizedName()); addCell(getLocalizedMessate("label.module.workingCapital.unit.responsible"), getUnitResponsibles(workingCapital)); addCell(getLocalizedMessate("label.module.workingCapital.initialization.accountingUnit"), accountingUnit == null ? "" : accountingUnit.getName()); addCell(getLocalizedMessate("label.module.workingCapital.requestingDate"), initialization.getRequestCreation().toString("yyyy-MM-dd HH:mm:ss")); addCell(getLocalizedMessate("label.module.workingCapital.requester"), initialization.getRequestor().getName()); final Person movementResponsible = workingCapital.getMovementResponsible(); addCell(getLocalizedMessate("label.module.workingCapital.movementResponsible"), movementResponsible == null ? "" : movementResponsible.getName()); addCell(getLocalizedMessate("label.module.workingCapital.fiscalId"), initialization.getFiscalId()); addCell(getLocalizedMessate("label.module.workingCapital.internationalBankAccountNumber"), initialization.getInternationalBankAccountNumber()); addCell(getLocalizedMessate("label.module.workingCapital.fundAllocationId"), initialization.getFundAllocationId()); final Money requestedAnualValue = initialization.getRequestedAnualValue(); addCell(getLocalizedMessate("label.module.workingCapital.requestedAnualValue.requested"), requestedAnualValue); addCell(getLocalizedMessate("label.module.workingCapital.requestedMonthlyValue.requested"), requestedAnualValue.divideAndRound(new BigDecimal(6))); final Money authorizedAnualValue = initialization.getAuthorizedAnualValue(); addCell(getLocalizedMessate("label.module.workingCapital.authorizedAnualValue"), authorizedAnualValue == null ? "" : authorizedAnualValue); final Money maxAuthorizedAnualValue = initialization.getMaxAuthorizedAnualValue(); addCell(getLocalizedMessate("label.module.workingCapital.maxAuthorizedAnualValue"), maxAuthorizedAnualValue == null ? "" : maxAuthorizedAnualValue); final DateTime lastSubmission = initialization.getLastSubmission(); addCell(getLocalizedMessate("label.module.workingCapital.initialization.lastSubmission"), lastSubmission == null ? "" : lastSubmission.toString("yyyy-MM-dd")); final DateTime refundRequested = initialization.getRefundRequested(); addCell(getLocalizedMessate("label.module.workingCapital.initialization.refundRequested"), refundRequested == null ? "" : refundRequested.toString("yyyy-MM-dd")); final WorkingCapitalTransaction lastTransaction = workingCapital.getLastTransaction(); if (lastTransaction == null) { addCell(getLocalizedMessate("label.module.workingCapital.transaction.accumulatedValue"), Money.ZERO); addCell(getLocalizedMessate("label.module.workingCapital.transaction.balance"), Money.ZERO); addCell(getLocalizedMessate("label.module.workingCapital.transaction.debt"), Money.ZERO); } else { addCell(getLocalizedMessate("label.module.workingCapital.transaction.accumulatedValue"), lastTransaction.getAccumulatedValue()); addCell(getLocalizedMessate("label.module.workingCapital.transaction.balance"), lastTransaction.getBalance()); addCell(getLocalizedMessate("label.module.workingCapital.transaction.debt"), lastTransaction.getDebt()); } for (final AcquisitionClassification classification : WorkingCapitalSystem.getInstance() .getAcquisitionClassificationsSet()) { final String description = classification.getDescription(); final String pocCode = classification.getPocCode(); final String key = pocCode + " - " + description; final Money value = calculateValueForClassification(workingCapital, classification); addCell(key, value); } } private Money calculateValueForClassification(final WorkingCapital workingCapital, final AcquisitionClassification classification) { Money result = Money.ZERO; for (final WorkingCapitalTransaction transaction : workingCapital .getWorkingCapitalTransactionsSet()) { if (transaction.isAcquisition()) { final WorkingCapitalAcquisitionTransaction acquisitionTransaction = (WorkingCapitalAcquisitionTransaction) transaction; final WorkingCapitalAcquisition acquisition = acquisitionTransaction .getWorkingCapitalAcquisition(); final AcquisitionClassification acquisitionClassification = acquisition .getAcquisitionClassification(); if (acquisitionClassification == classification) { result = result.add(acquisition.getValueAllocatedToSupplier()); } } } return result; } private String getUnitResponsibles(final WorkingCapital workingCapital) { final StringBuilder builder = new StringBuilder(); final SortedMap<Person, Set<Authorization>> authorizations = workingCapital .getSortedAuthorizations(); if (!authorizations.isEmpty()) { for (final Entry<Person, Set<Authorization>> entry : authorizations.entrySet()) { if (builder.length() > 0) { builder.append("; "); } builder.append(entry.getKey().getName()); } } return builder.toString(); } }; final LocalDate currentLocalDate = new LocalDate(); final SpreadsheetBuilder builder = new SpreadsheetBuilder(); builder.addConverter(Money.class, new CellConverter() { @Override public Object convert(final Object source) { final Money money = (Money) source; return money == null ? null : new Double( money.getValue().round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue()); } }); builder.addSheet(getLocalizedMessate("label.module.workingCapital") + " " + year + " - " + currentLocalDate.toString(), sheetData); final List<WorkingCapitalTransaction> transactions = new ArrayList<WorkingCapitalTransaction>(); for (final WorkingCapitalProcess process : processes) { final WorkingCapital workingCapital = process.getWorkingCapital(); transactions.addAll(workingCapital.getSortedWorkingCapitalTransactions()); } final SheetData<WorkingCapitalTransaction> transactionsSheet = new SheetData<WorkingCapitalTransaction>( transactions) { @Override protected void makeLine(WorkingCapitalTransaction transaction) { final WorkingCapital workingCapital = transaction.getWorkingCapital(); final WorkingCapitalProcess workingCapitalProcess = workingCapital.getWorkingCapitalProcess(); addCell(getLocalizedMessate("label.module.workingCapital.year"), year); addCell(getLocalizedMessate("label.module.workingCapital"), workingCapitalProcess.getWorkingCapital().getUnit().getPresentationName()); addCell(getLocalizedMessate("label.module.workingCapital.transaction.number"), transaction.getNumber()); addCell(getLocalizedMessate("WorkingCapitalProcessState.CANCELED"), transaction.isCanceledOrRejected() ? getLocalizedMessate("label.yes") : getLocalizedMessate("label.no")); addCell(getLocalizedMessate("label.module.workingCapital.transaction.description") + " " + getLocalizedMessate("label.module.workingCapital.transaction.number"), transaction.getDescription()); addCell(getLocalizedMessate("label.module.workingCapital.transaction.approval"), approvalLabel(transaction)); addCell(getLocalizedMessate("label.module.workingCapital.transaction.verification"), verificationLabel(transaction)); addCell(getLocalizedMessate("label.module.workingCapital.transaction.value"), transaction.getValue()); addCell(getLocalizedMessate("label.module.workingCapital.transaction.accumulatedValue"), transaction.getAccumulatedValue()); addCell(getLocalizedMessate("label.module.workingCapital.transaction.balance"), transaction.getBalance()); addCell(getLocalizedMessate("label.module.workingCapital.transaction.debt"), transaction.getDebt()); if (transaction.isAcquisition()) { final WorkingCapitalAcquisitionTransaction acquisitionTx = (WorkingCapitalAcquisitionTransaction) transaction; final WorkingCapitalAcquisition acquisition = acquisitionTx.getWorkingCapitalAcquisition(); final AcquisitionClassification acquisitionClassification = acquisition .getAcquisitionClassification(); final String economicClassification = acquisitionClassification.getEconomicClassification(); final String pocCode = acquisitionClassification.getPocCode(); addCell(getLocalizedMessate( "label.module.workingCapital.configuration.acquisition.classifications.economicClassification"), economicClassification); addCell(getLocalizedMessate( "label.module.workingCapital.configuration.acquisition.classifications.pocCode"), pocCode); addCell(getLocalizedMessate( "label.module.workingCapital.configuration.acquisition.classifications.description"), acquisition.getDescription()); } } private Object verificationLabel(final WorkingCapitalTransaction transaction) { if (transaction.isAcquisition()) { final WorkingCapitalAcquisitionTransaction acquisition = (WorkingCapitalAcquisitionTransaction) transaction; if (acquisition.getWorkingCapitalAcquisition().getVerified() != null) { return getLocalizedMessate("label.verified"); } if (acquisition.getWorkingCapitalAcquisition().getNotVerified() != null) { return getLocalizedMessate("label.notVerified"); } } return "-"; } private String approvalLabel(final WorkingCapitalTransaction transaction) { if (transaction.isAcquisition()) { final WorkingCapitalAcquisitionTransaction acquisition = (WorkingCapitalAcquisitionTransaction) transaction; if (acquisition.getWorkingCapitalAcquisition().getApproved() != null) { return getLocalizedMessate("label.approved"); } if (acquisition.getWorkingCapitalAcquisition().getRejectedApproval() != null) { return getLocalizedMessate("label.rejected"); } } return "-"; } }; builder.addSheet(getLocalizedMessate("label.module.workingCapital.transactions"), transactionsSheet); return streamSpreadsheet(response, "FundosManeio_" + year + "-" + currentLocalDate.getDayOfMonth() + "-" + currentLocalDate.getMonthOfYear() + "-" + currentLocalDate.getYear(), builder); }