Example usage for java.math BigDecimal toString

List of usage examples for java.math BigDecimal toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns the string representation of this BigDecimal , using scientific notation if an exponent is needed.

Usage

From source file:org.apache.roller.weblogger.business.FileContentManagerImpl.java

/**
 * @see org.apache.roller.weblogger.model.FileContentManager#canSave(
 * weblog, java.lang.String, java.lang.String, long, messages)
 *//* w  w  w.  j  ava2  s.c  o  m*/
public boolean canSave(Weblog weblog, String fileName, String contentType, long size, RollerMessages messages) {

    // first check, is uploading enabled?
    if (!WebloggerRuntimeConfig.getBooleanProperty("uploads.enabled")) {
        messages.addError("error.upload.disabled");
        return false;
    }

    // second check, does upload exceed max size for file?
    BigDecimal maxFileMB = new BigDecimal(WebloggerRuntimeConfig.getProperty("uploads.file.maxsize"));
    int maxFileBytes = (int) (1024000 * maxFileMB.doubleValue());
    log.debug("max allowed file size = " + maxFileBytes);
    log.debug("attempted save file size = " + size);
    if (size > maxFileBytes) {
        String[] args = { fileName, maxFileMB.toString() };
        messages.addError("error.upload.filemax", args);
        return false;
    }

    // third check, does file cause weblog to exceed quota?
    BigDecimal maxDirMB = new BigDecimal(WebloggerRuntimeConfig.getProperty("uploads.dir.maxsize"));
    long maxDirBytes = (long) (1024000 * maxDirMB.doubleValue());
    try {
        File storageDir = this.getRealFile(weblog, null);
        long userDirSize = getDirSize(storageDir, true);
        if (userDirSize + size > maxDirBytes) {
            messages.addError("error.upload.dirmax", maxDirMB.toString());
            return false;
        }
    } catch (Exception ex) {
        // shouldn't ever happen, means the weblogs uploads dir is bad somehow
        // rethrow as a runtime exception
        throw new RuntimeException(ex);
    }

    // fourth check, is upload type allowed?
    String allows = WebloggerRuntimeConfig.getProperty("uploads.types.allowed");
    String forbids = WebloggerRuntimeConfig.getProperty("uploads.types.forbid");
    String[] allowFiles = StringUtils.split(StringUtils.deleteWhitespace(allows), ",");
    String[] forbidFiles = StringUtils.split(StringUtils.deleteWhitespace(forbids), ",");
    if (!checkFileType(allowFiles, forbidFiles, fileName, contentType)) {
        String[] args = { fileName, contentType };
        messages.addError("error.upload.forbiddenFile", args);
        return false;
    }

    return true;
}

From source file:org.kuali.kpme.pm.position.validation.PositionValidation.java

protected boolean validateResponsibilityListPercentage(PositionBo aPosition) {
    if (CollectionUtils.isNotEmpty(aPosition.getPositionResponsibilityList())) {
        BigDecimal sum = BigDecimal.ZERO;
        for (PositionResponsibilityBo aResp : aPosition.getPositionResponsibilityList()) {
            if (aResp != null && aResp.getPercentTime() != null) {
                sum = sum.add(aResp.getPercentTime());
            }/*from  w  ww  . j  av a  2  s .  co  m*/
        }
        if (sum.compareTo(new BigDecimal(100)) > 0) {
            String[] parameters = new String[1];
            parameters[0] = sum.toString();
            this.putFieldError("dataObject.positionResponsibilityList",
                    "responsibility.percenttime.exceedsMaximum", parameters);
            return false;
        }
    }
    return true;
}

From source file:com.repay.android.frienddetails.FriendActivity.java

private void clearAllDebts() {
    AlertDialog.Builder clearDebtDialog = new AlertDialog.Builder(this);
    clearDebtDialog.setTitle(R.string.clear_debt);
    clearDebtDialog.setMessage(R.string.are_you_sure);
    clearDebtDialog.setPositiveButton(R.string.clear_debt, new OnClickListener() {
        @Override/*  w ww.j  a  va2  s . c o m*/
        public void onClick(DialogInterface dialog, int which) {
            try {
                BigDecimal debtRepayed = mFriend.getDebt().negate();
                mDB.addDebt(mFriend.getRepayID(), debtRepayed, "Repaid");
                mFriend.setDebt(mFriend.getDebt().add(debtRepayed));
                mDB.updateFriendRecord(mFriend);
                Toast.makeText(getApplicationContext(),
                        "Debt of " + SettingsFragment.getCurrencySymbol(getApplicationContext())
                                + debtRepayed.toString() + " cleared",
                        Toast.LENGTH_SHORT).show();
                finish();
            } catch (Throwable e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
    });
    clearDebtDialog.setNegativeButton(R.string.cancel, new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    clearDebtDialog.show();
}

From source file:CSVWriter.java

private String handleBigDecimal(BigDecimal decimal) {
    return decimal == null ? "" : decimal.toString();
}

From source file:org.egov.egf.web.actions.budget.BudgetSearchAction.java

public String divideAndRoundBigDecToString(final BigDecimal amount) {
    BigDecimal value = amount;
    value = value.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
    return value.toString();
}

From source file:fragment.web.HomeControllerTest.java

/**
 * @author Abhaik/*ww  w.j  a  va  2 s .  c  o  m*/
 * @description : Test to get Home Items for Tenant Normal User with Null Service Instance
 */
@Test
public void testGetHomeItemsForNormalUserWithInstantNullAsNormalUser() {

    User user = userDAO.find(22L);
    asUser(user);

    Tenant tenant = tenantDAO.find(20L);
    request.setAttribute("effectiveTenant", tenant);
    request.setAttribute("isSurrogatedTenant", Boolean.FALSE);
    List<com.vmops.model.Subscription> activeSubscriptionList = subscriptionService
            .findAllSubscriptionsByState(tenant, user, null, null, 1, 10000, State.ACTIVE);

    String resultString = controller.getHomeItems(tenant, tenant.getParam(), null, map, request);
    Assert.assertNotNull(resultString);
    Assert.assertEquals("home.items.view", resultString);

    BigDecimal currentSpend = (BigDecimal) map.get("currentSpend");
    Assert.assertEquals("250.0000", currentSpend.toString());

    List<Map<String, Object>> dashboardItemsList = (List<Map<String, Object>>) map.get("dashboardItems");
    for (int i = 0; i < dashboardItemsList.size(); i++) {
        Map<String, Object> dashboardItems = dashboardItemsList.get(i);
        Assert.assertFalse(dashboardItems.get("itemName").equals("label.active.users"));
        if (dashboardItems.get("itemName").equals("label.active.subscriptions")) {
            Assert.assertEquals(activeSubscriptionList.size(), dashboardItems.get("itemValue"));
        }
        if (dashboardItems.get("itemName").equals("label.total.spend")) {
            Assert.assertEquals("250.0000", dashboardItems.get("itemValue").toString());
        }
    }
}

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

/**
 * Create Facts (the accounting logic) for MMS, MMR.
 * /*from  www  .j  a  v  a  2 s .c o m*/
 * <pre>
 *  Shipment
 *      CoGS            DR
 *      Inventory               CR
 *  Shipment of Project Issue
 *      CoGS            DR
 *      Project                 CR
 *  Receipt
 *      Inventory       DR
 *      NotInvoicedReceipt      CR
 * </pre>
 * 
 * @param as
 *          accounting schema
 * @return Fact
 */
public Fact createFact(AcctSchema as, ConnectionProvider conn, Connection con, VariablesSecureApp vars)
        throws ServletException {
    // Select specific definition
    String strClassname = AcctServerData.selectTemplateDoc(conn, as.m_C_AcctSchema_ID, DocumentType);
    if (strClassname.equals(""))
        strClassname = AcctServerData.selectTemplate(conn, as.m_C_AcctSchema_ID, AD_Table_ID);
    if (!strClassname.equals("")) {
        try {
            DocLCCostTemplate newTemplate = (DocLCCostTemplate) Class.forName(strClassname).newInstance();
            return newTemplate.createFact(this, as, conn, con, vars);
        } catch (Exception e) {
            log4j.error("Error while creating new instance for DocLCCostTemplate - " + e);
        }
    }
    C_Currency_ID = as.getC_Currency_ID();
    int stdPrecision = 0;
    OBContext.setAdminMode(true);
    try {
        stdPrecision = OBDal.getInstance().get(Currency.class, this.C_Currency_ID).getStandardPrecision()
                .intValue();
    } finally {
        OBContext.restorePreviousMode();
    }

    // create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    String Fact_Acct_Group_ID = SequenceIdData.getUUID();
    String amtDebit = "0";
    String amtCredit = "0";
    DocLine_LCCost line = null;
    Account acctLC = null;
    BigDecimal totalAmount = BigDecimal.ZERO;
    // Lines
    // Added lines: amt to credit, account: landed cost account (with dimensions)
    for (int i = 0; p_lines != null && i < p_lines.length; i++) {
        line = (DocLine_LCCost) p_lines[i];

        BigDecimal amount = new BigDecimal(line.getAmount()).setScale(stdPrecision, BigDecimal.ROUND_HALF_UP);
        acctLC = getLandedCostAccount(line.getLandedCostTypeId(), amount, as, conn);

        log4jDocLCCost.debug("previous to creteline, line.getAmount(): " + line.getAmount());

        amtDebit = "";
        amtCredit = amount.toString();

        fact.createLine(line, acctLC, line.m_C_Currency_ID, amtDebit, amtCredit, Fact_Acct_Group_ID,
                nextSeqNo(SeqNo), DocumentType, line.m_DateAcct, null, conn);

        totalAmount = totalAmount.add(amount);

    }

    // added one line: amt to debit, account: landed cost account (without dimensions)
    if (totalAmount.compareTo(BigDecimal.ZERO) != 0) {
        DocLine line2 = new DocLine(DocumentType, Record_ID, line.m_TrxLine_ID);
        line2.copyInfo(line);

        line2.m_C_BPartner_ID = "";
        line2.m_M_Product_ID = "";
        line2.m_C_Project_ID = "";
        line2.m_C_Costcenter_ID = "";
        line2.m_User1_ID = "";
        line2.m_User2_ID = "";
        line2.m_C_Activity_ID = "";
        line2.m_C_Campaign_ID = "";
        line2.m_A_Asset_ID = "";

        fact.createLine(line2, acctLC, line2.m_C_Currency_ID,
                "Y".equals(line.getIsMatchingAdjusted()) ? totalAmount.add(differenceAmt).toString()
                        : totalAmount.toString(),
                amtDebit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line2.m_DateAcct, null, conn);
    }

    // if there is difference between matched amt and cost amt, then accounting is generated
    if (differenceAmt.compareTo(BigDecimal.ZERO) != 0) {
        // if cost adjustment has been generated, then the account is distributed between the goods
        // shipments lines
        if ("Y".equals(line.getIsMatchingAdjusted())) {
            DocLineLCCostData[] dataRcptLineAmt = DocLineLCCostData.selectRcptLineAmt(conn, line.getLcCostId());

            for (int j = 0; j < dataRcptLineAmt.length; j++) {
                DocLineLCCostData lineRcpt = dataRcptLineAmt[j];

                BigDecimal rcptAmount = new BigDecimal(lineRcpt.amount).setScale(stdPrecision,
                        BigDecimal.ROUND_HALF_UP);
                amtDebit = "";
                amtCredit = rcptAmount.toString();

                DocLine line4 = new DocLine(DocumentType, Record_ID, line.m_TrxLine_ID);
                line4.copyInfo(line);
                line4.m_C_BPartner_ID = "";
                line4.m_M_Product_ID = lineRcpt.mProductId;
                line4.m_C_Project_ID = "";
                line4.m_C_Costcenter_ID = "";
                line4.m_User1_ID = "";
                line4.m_User2_ID = "";
                line4.m_C_Activity_ID = "";
                line4.m_C_Campaign_ID = "";
                line4.m_A_Asset_ID = "";

                ProductInfo p = new ProductInfo(line4.m_M_Product_ID, conn);

                // If transaction uses Standard Algorithm IPD account will be used, else Asset account
                LandedCostCost landedCostCost = OBDal.getInstance().get(LandedCostCost.class,
                        line.m_TrxHeader_ID);
                Organization org = OBContext.getOBContext()
                        .getOrganizationStructureProvider(landedCostCost.getClient().getId())
                        .getLegalEntity(landedCostCost.getOrganization());
                Account account = null;
                if (StringUtils.equals(
                        CostingUtils.getCostDimensionRule(org, landedCostCost.getCreationDate())
                                .getCostingAlgorithm().getJavaClassName(),
                        "org.openbravo.costing.StandardAlgorithm")) {
                    account = p.getAccount(ProductInfo.ACCTTYPE_P_IPV, as, conn);
                } else {
                    account = p.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn);
                }

                fact.createLine(line4, account, line4.m_C_Currency_ID, amtCredit, amtDebit, Fact_Acct_Group_ID,
                        nextSeqNo(SeqNo), DocumentType, line4.m_DateAcct, null, conn);

            }

        }
    }

    SeqNo = "0";
    return fact;
}

From source file:com.repay.android.frienddetails.FriendDetailsActivity.java

private void clearAllDebts() {
    AlertDialog.Builder clearDebtDialog = new AlertDialog.Builder(this);
    clearDebtDialog.setTitle(R.string.activity_friendoverview_clearDebtDialog_title);
    clearDebtDialog.setMessage(R.string.activity_friendoverview_clearDebtDialog_message);
    clearDebtDialog.setPositiveButton(R.string.activity_friendoverview_clearDebtDialog_yes,
            new OnClickListener() {
                @Override/*from   ww  w  .j a  v  a 2  s .  c o  m*/
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        BigDecimal debtRepayed = mFriend.getDebt().negate();
                        mDB.addDebt(mFriend.getRepayID(), debtRepayed, "Repaid");
                        mFriend.setDebt(mFriend.getDebt().add(debtRepayed));
                        mDB.updateFriendRecord(mFriend);
                        Toast.makeText(getApplicationContext(),
                                "Debt of \u00A3" + debtRepayed.toString() + " cleared", Toast.LENGTH_SHORT)
                                .show();
                        requestBackup();
                        finish();
                    } catch (Throwable e) {
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.e(TAG, e.getMessage());
                        e.printStackTrace();
                    }
                }
            });
    clearDebtDialog.setNegativeButton(R.string.activity_friendoverview_clearDebtDialog_no,
            new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    clearDebtDialog.show();
}

From source file:ru.neverdark.phototools.fragments.DofFragment.java

/**
 * @return aperture value from aperture wheel
 *///w w w.j a v a  2  s.c o m
private BigDecimal getAperture() {
    BigDecimal aperture = new BigDecimal(
            Array.SCIENTIFIC_ARERTURES[Array.getApertureIndex((String) mWheelAperture.getSelectedItem())]);
    Log.variable("aperture", aperture.toString());
    return aperture;
}

From source file:org.egov.egf.web.actions.contra.ContraBTCAction.java

HashMap<String, Object> populateDetailMap(final String glCode, final BigDecimal creditAmount,
        final BigDecimal debitAmount) {
    final HashMap<String, Object> detailMap = new HashMap<String, Object>();
    detailMap.put(VoucherConstant.CREDITAMOUNT, creditAmount.toString());
    detailMap.put(VoucherConstant.DEBITAMOUNT, debitAmount.toString());
    detailMap.put(VoucherConstant.GLCODE, glCode);
    return detailMap;
}