Example usage for java.math BigDecimal abs

List of usage examples for java.math BigDecimal abs

Introduction

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

Prototype

public BigDecimal abs() 

Source Link

Document

Returns a BigDecimal whose value is the absolute value of this BigDecimal , and whose scale is this.scale() .

Usage

From source file:org.efaps.esjp.accounting.transaction.evaluation.DocumentInfo_Base.java

/**
 * Setter method for instance variable {@link #rounding}.
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @throws EFapsException on error/*from w w  w.  j  a  va2 s  . c  o m*/
 */
public void applyRounding(final Parameter _parameter) throws EFapsException {
    if (!isValid(_parameter)) {
        final Period period = new Period();
        final Instance periodInst = period.evaluateCurrentPeriod(_parameter);
        // is does not sum to 0 but is less then the max defined
        final Properties props = Accounting.getSysConfig().getObjectAttributeValueAsProperties(periodInst);
        final BigDecimal diffMax = new BigDecimal(
                props.getProperty(AccountingSettings.PERIOD_ROUNDINGMAXAMOUNT, "0"));
        final BigDecimal diff = getDebitSum(_parameter).subtract(getCreditSum(_parameter));
        if (diffMax.compareTo(diff.abs()) > 0) {
            final boolean debit = diff.compareTo(BigDecimal.ZERO) < 0;
            final AccountInfo accInfo;
            if (debit) {
                accInfo = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_ROUNDINGDEBIT);
            } else {
                accInfo = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_ROUNDINGCREDIT);
            }
            if (accInfo != null) {
                accInfo.setAmount(diff.abs());
                accInfo.setAmountRate(diff.abs());
                final CurrencyInst currInst = period.getCurrency(periodInst);
                accInfo.setCurrInstance(currInst.getInstance());
                accInfo.setRateInfo(RateInfo.getDummyRateInfo(), "");
                if (debit) {
                    addDebit(accInfo);
                } else {
                    addCredit(accInfo);
                }
            }
        }
    }
}

From source file:org.kuali.kfs.module.endow.batch.service.impl.GeneralLedgerInterfaceBatchProcessServiceImpl.java

/**
 * method to create a gain/loss record when document type = EAD...
 * @param oef OriginEntryFull/* w w w . ja  va  2s.c  om*/
 * @param transactionArchive
 * @param OUTPUT_KEM_TO_GL_DATA_FILE_ps the output file
 * @param statisticsDataRow
 * @return success true if successfully created offset or gain loss entry else false
 */
protected boolean createGainLossEntry(OriginEntryFull oef, GlInterfaceBatchProcessKemLine transactionArchive,
        PrintStream OUTPUT_KEM_TO_GL_DATA_FILE_ps,
        GLInterfaceBatchStatisticsReportDetailTableRow statisticsDataRow) {
    boolean success = true;

    //need to create an net gain/loss entry...if document type name = EAD....
    if (transactionArchive.getTypeCode()
            .equalsIgnoreCase(EndowConstants.DocumentTypeNames.ENDOWMENT_ASSET_DECREASE)) {
        oef.setFinancialObjectCode(
                parameterService.getParameterValueAsString(GeneralLedgerInterfaceBatchProcessStep.class,
                        EndowParameterKeyConstants.GLInterfaceBatchProcess.CASH_SALE_GAIN_LOSS_OBJECT_CODE));
        BigDecimal transactionAmount = transactionArchive.getShortTermGainLoss()
                .add(transactionArchive.getLongTermGainLoss());
        oef.setTransactionLedgerEntryAmount(new KualiDecimal(transactionAmount.abs()));
        oef.setTransactionDebitCreditCode(getTransactionDebitCreditCodeForOffSetEntry(transactionAmount));
        try {
            createOutputEntry(oef, OUTPUT_KEM_TO_GL_DATA_FILE_ps);
            statisticsDataRow.increaseGLEntriesGeneratedCount();

            GlInterfaceBatchProcessKemLine transactionArchiveLossGain = new GlInterfaceBatchProcessKemLine();
            transactionArchiveLossGain.setTypeCode(transactionArchive.getTypeCode());
            transactionArchiveLossGain.setChartCode(transactionArchive.getChartCode());
            transactionArchiveLossGain.setObjectCode(oef.getFinancialObjectCode());
            transactionArchiveLossGain.setShortTermGainLoss(transactionArchive.getShortTermGainLoss());
            transactionArchiveLossGain.setLongTermGainLoss(transactionArchive.getLongTermGainLoss());
            transactionArchiveLossGain.setSubTypeCode(transactionArchive.getSubTypeCode());
            transactionArchiveLossGain.setHoldingCost(transactionArchive.getHoldingCost());
            transactionArchiveLossGain
                    .setTransactionArchiveIncomeAmount(transactionArchive.getTransactionArchiveIncomeAmount());
            transactionArchiveLossGain.setTransactionArchivePrincipalAmount(
                    transactionArchive.getTransactionArchivePrincipalAmount());

            updateTotalsProcessed(transactionArchiveLossGain);
        } catch (Exception ex) {
            //write the error details to the exception report...
            statisticsDataRow.increaseNumberOfExceptionsCount();
            writeExceptionRecord(transactionArchive, ex.getMessage());
            success = false;
        }
    }

    return success;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hypotenuse./*from www.  j  av  a  2 s  . c om*/
 *
 * @param x the first argument.
 * @param y the second argument.
 * @return the square root of the sum of the squares of the two arguments, sqrt(x^2+y^2).
 */
static public BigDecimal hypot(final BigDecimal x, final BigDecimal y) {
    /* compute x^2+y^2
     */
    BigDecimal z = x.pow(2).add(y.pow(2));
    /* truncate to the precision set by x and y. Absolute error = 2*x*xerr+2*y*yerr,
     * where the two errors are 1/2 of the ulps. Two intermediate protectio digits.
     */
    BigDecimal zerr = x.abs().multiply(x.ulp()).add(y.abs().multiply(y.ulp()));
    MathContext mc = new MathContext(2 + err2prec(z, zerr));
    /* Pull square root */
    z = sqrt(z.round(mc));
    /* Final rounding. Absolute error in the square root is (y*yerr+x*xerr)/z, where zerr holds 2*(x*xerr+y*yerr).
     */
    mc = new MathContext(err2prec(z.doubleValue(), 0.5 * zerr.doubleValue() / z.doubleValue()));
    return z.round(mc);
}

From source file:org.efaps.esjp.accounting.transaction.FieldValue_Base.java

/**
 * Gets the value sum.// w ww  .  j  av a2  s.  com
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @return the value sum
 * @throws EFapsException on error
 */
public Return getValueSum(final Parameter _parameter) throws EFapsException {
    final Return ret = new Return();

    final QueryBuilder queryBldr = getQueryBldrFromProperties(_parameter);
    final MultiPrintQuery multi = queryBldr.getPrint();
    multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount);
    multi.execute();

    BigDecimal value = BigDecimal.ZERO;

    while (multi.next()) {
        final BigDecimal amount = multi
                .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount);
        value = value.add(amount.abs());
    }
    ret.put(ReturnValues.VALUES, value);
    return ret;
}

From source file:org.openbravo.erpCommon.ad_forms.Fact.java

/**
 * Balance Source Segment/*from   ww  w  .j av a 2s.c o m*/
 * 
 * @param segmentType
 *          segment type
 */
private void balanceSegment(String segmentType, ConnectionProvider conn) {
    // no lines -> balanced
    if (m_lines.size() == 0)
        return;
    log4jFact.debug("balanceSegment (" + segmentType + ") - ");
    // Org
    if (segmentType.equals(AcctSchemaElement.SEGMENT_Org)) {
        HashMap<String, BigDecimal> map = new HashMap<String, BigDecimal>();
        // Add up values by key
        for (int i = 0; i < m_lines.size(); i++) {
            FactLine line = (FactLine) m_lines.get(i);
            String key = line.getAD_Org_ID(conn);
            BigDecimal bal = line.getSourceBalance();
            BigDecimal oldBal = map.get(key);
            if (oldBal != null)
                bal = bal.add(oldBal);
            map.put(key, bal);
        }
        // Create entry for non-zero element
        Iterator<String> keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            BigDecimal diff = map.get(key);
            //
            if (diff.compareTo(ZERO) != 0) {
                // Create Balancing Entry
                if (m_lines.size() == 0) {
                    log4jFact.error("balanceSegment failed.");
                    return;
                }
                FactLine fl = (FactLine) m_lines.get(0);
                FactLine line = new FactLine(m_doc.AD_Table_ID, m_doc.Record_ID, "", fl.m_Fact_Acct_Group_ID,
                        fl.m_SeqNo, fl.m_DocBaseType);
                line.setDocumentInfo(m_doc, null);
                line.setJournalInfo(m_doc.GL_Category_ID);
                line.setPostingType(m_postingType);
                // Amount & Account
                if (diff.compareTo(ZERO) < 0) {
                    line.setAmtSource(m_doc.C_Currency_ID, diff.abs().toString(), ZERO.toString());
                    line.setAccount(m_acctSchema, m_acctSchema.m_DueFrom_Acct);
                } else {
                    line.setAmtSource(m_doc.C_Currency_ID, ZERO.toString(), diff.abs().toString());
                    line.setAccount(m_acctSchema, m_acctSchema.m_DueTo_Acct);
                }
                line.convert(m_acctSchema.getC_Currency_ID(), m_doc.DateAcct,
                        m_acctSchema.getCurrencyRateType(), conn);
                line.setAD_Org_ID(key);
                log4jFact.debug("balanceSegment (" + segmentType + ") - ");
                log4jFact.debug("************* fact - balanceSegment - m_lines.size() - " + m_lines.size()
                        + " - line.ad_org_id - " + line.getAD_Org_ID(conn));
                m_lines.add(line);
            }
        }
        map.clear();
    }
}

From source file:org.openbravo.erpCommon.ad_forms.Fact.java

/**
 * Balance Accounting Currency. If the accounting currency is not balanced, if Currency balancing
 * is enabled create a new line using the currency balancing account with zero source balance or
 * adjust the line with the largest balance sheet account or if no balance sheet account exist,
 * the line with the largest amount//from  w  ww .  jav a 2 s .  c  o  m
 * 
 * @return FactLine
 */
public FactLine balanceAccounting(ConnectionProvider conn) {
    BigDecimal diff = getAcctBalance();
    log4jFact.debug("balanceAccounting - Balance=" + diff);
    FactLine line = null;
    // Create Currency Entry
    if (m_acctSchema.isCurrencyBalancing()) {
        if (m_lines.size() == 0) {
            log4jFact.error("balanceAccounting failed.");
            return null;
        }
        FactLine fl = (FactLine) m_lines.get(0);
        line = new FactLine(m_doc.AD_Table_ID, m_doc.Record_ID, "", fl.m_Fact_Acct_Group_ID, fl.m_SeqNo,
                fl.m_DocBaseType);
        line.setDocumentInfo(m_doc, null);
        line.setJournalInfo(m_doc.GL_Category_ID);
        line.setPostingType(m_postingType);

        // Amount
        line.setAmtSource(m_doc.C_Currency_ID, ZERO.toString(), ZERO.toString());
        line.convert(m_acctSchema.getC_Currency_ID(), m_doc.DateAcct, m_acctSchema.getCurrencyRateType(), conn);
        if (diff.compareTo(ZERO) < 0)
            line.setAmtAcct(diff.abs().toString(), ZERO.toString());
        else
            line.setAmtAcct(ZERO.toString(), diff.abs().toString());
        line.setAccount(m_acctSchema, m_acctSchema.getCurrencyBalancing_Acct());
        log4jFact.debug("balanceAccounting - " + line.toString());
        log4jFact.debug("************* fact - balanceAccounting - m_lines.size() - " + m_lines.size());
        m_lines.add(line);
    } else { // Adjust biggest (Balance Sheet) line amount
        BigDecimal BSamount = ZERO;
        FactLine BSline = null;
        BigDecimal PLamount = ZERO;
        FactLine PLline = null;
        int signum = diff.signum();
        // Find line
        for (int i = 0; i < m_lines.size(); i++) {
            FactLine l = (FactLine) m_lines.get(i);
            BigDecimal amt = l.getAccountingBalance();
            // amt = amt.abs();
            if (l.isBalanceSheet() && ((amt.compareTo(BSamount) > 0 && signum != 1))
                    || ((amt.compareTo(BSamount) < 0 && signum == 1))) {
                BSamount = amt;
                BSline = l;
            } else if (!l.isBalanceSheet() && ((amt.compareTo(BSamount) > 0 && signum != 1))
                    || ((amt.compareTo(BSamount) < 0 && signum == 1))) {
                PLamount = amt;
                PLline = l;
            }
        }
        if (BSline != null)
            line = BSline;
        else
            line = PLline;

        if (line == null)
            log4jFact.error("balanceAccounting - No Line found");
        else {
            log4jFact.debug("Adjusting Amt=" + diff.toString() + "; Line=" + line.toString());
            line.currencyCorrect(diff);
            log4jFact.debug("balanceAccounting - " + line.toString());
        }
    } // correct biggest amount

    // Debug info only
    this.isAcctBalanced();

    return line;
}

From source file:com.heliumv.api.inventory.InventoryApi.java

/**
 * Mengen &uuml;berpr&uuml;fen</b>
 * <p>Die Gesamtsumme der identity.amount muss ident mit der angegebenen Menge sein<p>
 * <p>Es d&uuml;rfen nur positive Mengen in den identities vorhanden sein.</p>
 * <p>Seriennummernbehaftete Artikel d&uuml;rfen nur die Menge 1.0 haben</p>
 * @param amount/*from   w w w  .  jav a 2  s.  c  om*/
 * @param identities
 * @return
 */
private boolean verifyAmounts(ArtikelDto itemDto, BigDecimal amount, List<IdentityAmountEntry> identities) {
    if (!itemDto.istArtikelSnrOderchargentragend())
        return true;
    if (identities == null || identities.size() == 0) {
        respondBadRequestValueMissing("identities");
        return false;
    }

    BigDecimal amountIdentities = BigDecimal.ZERO;
    for (IdentityAmountEntry entry : identities) {
        if (entry.getAmount() == null) {
            respondBadRequestValueMissing("amount");
            appendBadRequestData(entry.getIdentity(), "amount missing");
            return false;
        }

        if (entry.getAmount().signum() != 1) {
            respondBadRequest("amount", "positive");
            appendBadRequestData(entry.getIdentity(), entry.getAmount().toPlainString());
            return false;
        }

        if (itemDto.isSeriennrtragend()) {
            if (BigDecimal.ONE.compareTo(entry.getAmount()) != 0) {
                respondBadRequest("snr-amount", "1 (is: " + entry.getAmount().toPlainString() + ")");
                return false;
            }
        }

        amountIdentities = amountIdentities.add(entry.getAmount());
    }

    if (amountIdentities.compareTo(amount.abs()) != 0) {
        respondBadRequest("totalamount != identityamount", amount.toPlainString());
        appendBadRequestData("identityamount", amountIdentities.toPlainString());
        return false;
    }

    return true;
}

From source file:nl.strohalm.cyclos.services.elements.MemberImportServiceImpl.java

private void processMember(final MemberImport memberImport, ImportedMember importedMember,
        final boolean sendActivationMail) {
    importedMember = fetchService.fetch(importedMember, ImportedMember.Relationships.CUSTOM_VALUES,
            ImportedMember.Relationships.RECORDS);

    // Fill the member
    Member member = new Member();
    final MemberUser user = new MemberUser();
    member.setUser(user);/*from  w ww . j  av a  2  s  . c om*/
    member.setCreationDate(importedMember.getCreationDate());
    member.setGroup(memberImport.getGroup());
    member.setName(importedMember.getName());
    user.setSalt(importedMember.getSalt());
    user.setUsername(importedMember.getUsername());
    user.setPassword(importedMember.getPassword());
    member.setEmail(importedMember.getEmail());

    // Set the custom values
    fetchService.fetch(importedMember.getCustomValues(), CustomFieldValue.Relationships.FIELD,
            CustomFieldValue.Relationships.POSSIBLE_VALUE);
    customFieldHelper.cloneFieldValues(importedMember, member);

    // Insert the member
    member = elementService.insertMember(member, !sendActivationMail, false);

    // If the member is active and there was an imported creation date, set the activation date = imported creation date
    if (member.getActivationDate() != null && importedMember.getCreationDate() != null) {
        member.setActivationDate(importedMember.getCreationDate());
    }

    // Insert the records
    final Collection<ImportedMemberRecord> records = importedMember.getRecords();
    if (records != null) {
        for (ImportedMemberRecord importedRecord : records) {
            importedRecord = fetchService.fetch(importedRecord,
                    ImportedMemberRecord.Relationships.CUSTOM_VALUES);
            final MemberRecord record = new MemberRecord();
            record.setElement(member);
            record.setType(importedRecord.getType());
            record.setCustomValues(new ArrayList<MemberRecordCustomFieldValue>());
            for (final ImportedMemberRecordCustomFieldValue importedValue : importedRecord.getCustomValues()) {
                final CustomField field = importedValue.getField();
                final MemberRecordCustomFieldValue recordValue = new MemberRecordCustomFieldValue();
                recordValue.setField(field);
                if (field.getType() == CustomField.Type.ENUMERATED) {
                    recordValue.setPossibleValue(importedValue.getPossibleValue());
                } else if (field.getType() == CustomField.Type.MEMBER) {
                    recordValue.setMemberValue(importedValue.getMemberValue());
                }
                record.getCustomValues().add(recordValue);
            }
            memberRecordService.insert(record);
        }
    }

    // Handle the account
    final MemberAccountType accountType = memberImport.getAccountType();
    if (accountType != null) {
        // Set the credit limit
        final CreditLimitDTO limit = new CreditLimitDTO();
        limit.setLimitPerType(Collections.singletonMap(accountType, importedMember.getCreditLimit()));
        limit.setUpperLimitPerType(Collections.singletonMap(accountType, importedMember.getUpperCreditLimit()));
        accountService.setCreditLimit(member, limit);

        // Create the initial balance transaction
        final BigDecimal initialBalance = importedMember.getInitialBalance();
        if (initialBalance != null) {
            final double balance = initialBalance.doubleValue();
            TransferDTO transfer = null;
            if (balance < 0 && memberImport.getInitialDebitTransferType() != null) {
                // Is a negative balance: use the debit TT
                transfer = new TransferDTO();
                transfer.setFromOwner(member);
                transfer.setToOwner(SystemAccountOwner.instance());
                transfer.setTransferType(memberImport.getInitialDebitTransferType());
            } else if (balance > 0 && memberImport.getInitialCreditTransferType() != null) {
                // Is a positive balance: use the credit TT
                transfer = new TransferDTO();
                transfer.setFromOwner(SystemAccountOwner.instance());
                transfer.setToOwner(member);
                transfer.setTransferType(memberImport.getInitialCreditTransferType());
            }
            if (transfer != null) {
                // If there was a transfer set, it will be used
                transfer.setAutomatic(true);
                transfer.setContext(TransactionContext.AUTOMATIC);
                transfer.setAmount(initialBalance.abs());
                transfer.setDescription(transfer.getTransferType().getDescription());
                paymentService.insertWithoutNotification(transfer);
            }
        }
    }
}

From source file:nl.strohalm.cyclos.services.accountfees.AccountFeeServiceImpl.java

@Override
public BigDecimal calculateAmount(final AccountFeeLog feeLog, final Member member) {
    AccountFee fee = feeLog.getAccountFee();

    if (!fee.getGroups().contains(member.getGroup())) {
        // The member is not affected by this fee log
        return null;
    }//from w  ww. j  av a2  s . c  o m

    final Period period = feeLog.getPeriod();
    final MemberAccountType accountType = fee.getAccountType();
    final ChargeMode chargeMode = fee.getChargeMode();
    final BigDecimal freeBase = fee.getFreeBase();

    // Calculate the charge amount
    BigDecimal chargedAmount = BigDecimal.ZERO;
    BigDecimal amount = BigDecimal.ZERO;
    Calendar endDate = (period != null) ? period.getEnd() : null;
    final AccountDateDTO balanceParams = new AccountDateDTO(member, accountType, endDate);
    if (chargeMode.isFixed()) {
        boolean charge = true;
        if (freeBase != null) {
            final BigDecimal balance = accountService.getBalance(balanceParams);
            if (balance.compareTo(freeBase) <= 0) {
                charge = false;
            }
        }
        // Fixed fee amount
        if (charge) {
            amount = feeLog.getAmount();
        }
    } else if (chargeMode.isBalance()) {
        // Percentage over balance
        final boolean positiveBalance = !chargeMode.isNegative();
        BigDecimal balance = accountService.getBalance(balanceParams);
        // Skip if balance is out of range
        boolean charge = true;
        // Apply the free base
        if (freeBase != null) {
            if (positiveBalance) {
                balance = balance.subtract(freeBase);
            } else {
                balance = balance.add(freeBase);
            }
        }
        // Check if something will be charged
        if ((positiveBalance && balance.compareTo(BigDecimal.ZERO) <= 0)
                || (!positiveBalance && balance.compareTo(BigDecimal.ZERO) >= 0)) {
            charge = false;
        }
        if (charge) {
            // Get the charged amount
            chargedAmount = feeLog.getAmountValue().apply(balance.abs());
            amount = settingsService.getLocalSettings().round(chargedAmount);
        }
    } else if (chargeMode.isVolume()) {
        // Percentage over average transactioned volume
        amount = calculateChargeOverTransactionedVolume(feeLog, member);
    }

    // Ensure the amount is valid
    final BigDecimal minPayment = paymentService.getMinimumPayment();
    if (amount.compareTo(minPayment) < 0) {
        amount = BigDecimal.ZERO;
    }
    return amount;
}

From source file:org.totschnig.myexpenses.activity.ExpenseEdit.java

protected void fillAmount(BigDecimal amount) {
    int signum = amount.signum();
    switch (signum) {
    case -1://from w w  w.  j  a  v  a 2 s  .  c  o  m
        amount = amount.abs();
        break;
    case 1:
        mType = INCOME;
    }
    if (!mNewInstance) {
        mAmountText.setAmount(amount);
    }
    mAmountText.requestFocus();
    mAmountText.selectAll();
}