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.egov.ptis.actions.reports.TitleTransferRegisterAction.java

/**
 * @param propertyMutation/*from w  ww .  j  ava2  s  .co  m*/
 * @param finyear
 * @return
 */
private TitleTransferReportResult PreparePropertyWiseInfo(final PropertyMutation propertyMutation,
        final CFinancialYear finyear) {
    final TitleTransferReportResult ttrObj = new TitleTransferReportResult();
    String ownerName = "";
    ttrObj.setAssessmentNo(propertyMutation.getBasicProperty().getUpicNo());
    if (propertyMutation.getTransfereeInfos() != null && propertyMutation.getTransfereeInfos().size() > 0) {
        String newOwnerName = "";
        for (final PropertyMutationTransferee usr : propertyMutation.getTransfereeInfos())
            newOwnerName = newOwnerName + usr.getTransferee().getName() + ",";
        ttrObj.setOwnerName(newOwnerName.substring(0, newOwnerName.length() - 1));
    }
    ttrObj.setDoorNo(propertyMutation.getBasicProperty().getAddress().getHouseNoBldgApt());
    ttrObj.setLocation(propertyMutation.getBasicProperty().getPropertyID().getLocality().getName());
    BigDecimal taxAmount = propertyTaxUtil.getPropertyTaxDetails(propertyMutation.getBasicProperty().getId(),
            finyear);
    if (null != taxAmount)
        ttrObj.setPropertyTax(taxAmount.toString());
    if (propertyMutation.getTransferorInfos() != null && propertyMutation.getTransferorInfos().size() > 0) {
        for (final User usr : propertyMutation.getTransferorInfos())
            ownerName = ownerName + usr.getName() + ",";
        ttrObj.setOldTitle(ownerName.substring(0, ownerName.length() - 1));
    }

    if (propertyMutation.getTransfereeInfos() != null && propertyMutation.getTransfereeInfos().size() > 0) {
        ownerName = "";
        for (final PropertyMutationTransferee usr : propertyMutation.getTransfereeInfos())
            ownerName = ownerName + usr.getTransferee().getName() + ",";
        ttrObj.setChangedTitle(ownerName.substring(0, ownerName.length() - 1));
    }
    ttrObj.setDateOfTransfer(sdf.format(propertyMutation.getLastModifiedDate()));
    ttrObj.setCommissionerOrder("APPROVED");
    ttrObj.setMutationFee(propertyMutation.getMutationFee());

    return ttrObj;
}

From source file:org.egov.collection.integration.pgi.AxisAdaptor.java

/**
 * This method invokes APIs to frame request object for the payment service passed as parameter
 *
 * @param serviceDetails//  w w  w  .  j  ava 2s . c  o  m
 * @param receiptHeader
 * @return
 */
@Override
public PaymentRequest createPaymentRequest(final ServiceDetails paymentServiceDetails,
        final ReceiptHeader receiptHeader) {
    LOGGER.debug("inside createPaymentRequest");
    final DefaultPaymentRequest paymentRequest = new DefaultPaymentRequest();
    final LinkedHashMap<String, String> fields = new LinkedHashMap<>(0);
    final StringBuilder requestURL = new StringBuilder();
    final BigDecimal amount = receiptHeader.getTotalAmount();
    final float rupees = Float.parseFloat(amount.toString());
    final Integer rupee = (int) rupees;
    final Float exponent = rupees - (float) rupee;
    final Integer paise = (int) (rupee * PAISE_RUPEE_CONVERTER.intValue()
            + exponent * PAISE_RUPEE_CONVERTER.intValue());
    final StringBuilder returnUrl = new StringBuilder();
    returnUrl.append(paymentServiceDetails.getCallBackurl()).append("?paymentServiceId=")
            .append(paymentServiceDetails.getId());
    fields.put(CollectionConstants.AXIS_ACCESS_CODE, collectionApplicationProperties.axisAccessCode());
    fields.put(CollectionConstants.AXIS_AMOUNT, paise.toString());
    fields.put(CollectionConstants.AXIS_COMMAND, collectionApplicationProperties.axisCommand());
    fields.put(CollectionConstants.AXIS_LOCALE, collectionApplicationProperties.axisLocale());
    fields.put(CollectionConstants.AXIS_MERCHANT_TXN_REF, ApplicationThreadLocals.getCityCode()
            + CollectionConstants.SEPARATOR_HYPHEN + receiptHeader.getId().toString());
    fields.put(CollectionConstants.AXIS_MERCHANT, collectionApplicationProperties.axisMerchant());
    fields.put(CollectionConstants.AXIS_ORDER_INFO, ApplicationThreadLocals.getCityCode()
            + CollectionConstants.SEPARATOR_HYPHEN + ApplicationThreadLocals.getCityName());
    fields.put(CollectionConstants.AXIS_RETURN_URL, returnUrl.toString());
    fields.put(CollectionConstants.AXIS_TICKET_NO, receiptHeader.getConsumerCode());
    fields.put(CollectionConstants.AXIS_VERSION, collectionApplicationProperties.axisVersion());
    final String axisSecureSecret = collectionApplicationProperties.axisSecureSecret();
    if (axisSecureSecret != null) {
        final String secureHash = hashAllFields(fields);
        fields.put(CollectionConstants.AXIS_SECURE_HASH, secureHash);
    }
    fields.put(CollectionConstants.AXIS_SECURE_HASHTYPE, CollectionConstants.AXIS_SECURE_HASHTYPE_VALUE);

    requestURL.append(paymentServiceDetails.getServiceUrl()).append('?');
    appendQueryFields(requestURL, fields);
    paymentRequest.setParameter(CollectionConstants.ONLINEPAYMENT_INVOKE_URL, requestURL);
    LOGGER.info("AXIS payment gateway request: " + paymentRequest.getRequestParameters());
    return paymentRequest;
}

From source file:org.pentaho.di.trans.steps.terafast.TeraFast.java

/**
 * Write a single row to the temporary data file.
 *
 * @param rowMetaInterface/*from  w w w.  j ava 2 s  .c om*/
 *          describe the row of data
 *
 * @param row
 *          row entries
 * @throws KettleException
 *           ...
 */
public void writeToDataFile(RowMetaInterface rowMetaInterface, Object[] row) throws KettleException {
    // Write the data to the output
    ValueMetaInterface valueMeta = null;

    for (int i = 0; i < row.length; i++) {
        if (row[i] == null) {
            break; // no more rows
        }
        valueMeta = rowMetaInterface.getValueMeta(i);
        if (row[i] != null) {
            switch (valueMeta.getType()) {
            case ValueMetaInterface.TYPE_STRING:
                String s = rowMetaInterface.getString(row, i);
                dataFilePrintStream.print(pad(valueMeta, s.toString()));
                break;
            case ValueMetaInterface.TYPE_INTEGER:
                Long l = rowMetaInterface.getInteger(row, i);
                dataFilePrintStream.print(pad(valueMeta, l.toString()));
                break;
            case ValueMetaInterface.TYPE_NUMBER:
                Double d = rowMetaInterface.getNumber(row, i);
                dataFilePrintStream.print(pad(valueMeta, d.toString()));
                break;
            case ValueMetaInterface.TYPE_BIGNUMBER:
                BigDecimal bd = rowMetaInterface.getBigNumber(row, i);
                dataFilePrintStream.print(pad(valueMeta, bd.toString()));
                break;
            case ValueMetaInterface.TYPE_DATE:
                Date dt = rowMetaInterface.getDate(row, i);
                dataFilePrintStream.print(simpleDateFormat.format(dt));
                break;
            case ValueMetaInterface.TYPE_BOOLEAN:
                Boolean b = rowMetaInterface.getBoolean(row, i);
                if (b.booleanValue()) {
                    dataFilePrintStream.print("Y");
                } else {
                    dataFilePrintStream.print("N");
                }
                break;
            case ValueMetaInterface.TYPE_BINARY:
                byte[] byt = rowMetaInterface.getBinary(row, i);
                dataFilePrintStream.print(byt);
                break;
            default:
                throw new KettleException(BaseMessages.getString(PKG, "TeraFast.Exception.TypeNotSupported",
                        valueMeta.getType()));
            }
        }
        dataFilePrintStream.print(FastloadControlBuilder.DATAFILE_COLUMN_SEPERATOR);
    }
    dataFilePrintStream.print(Const.CR);
}

From source file:com.silverpeas.util.MetadataExtractor.java

private void computeMp4Duration(Metadata metadata, MovieHeaderBox movieHeaderBox) {
    BigDecimal duration = BigDecimal.valueOf(movieHeaderBox.getDuration());
    if (duration.intValue() > 0) {
        BigDecimal divisor = BigDecimal.valueOf(movieHeaderBox.getTimescale());

        // Duration
        duration = duration.divide(divisor, 10, BigDecimal.ROUND_HALF_DOWN);
        // get duration in ms
        duration = duration.multiply(BigDecimal.valueOf(1000));
        metadata.add(XMPDM.DURATION, duration.toString());
    }// ww  w. j av a  2 s.  c o  m
}

From source file:net.ceos.project.poi.annotated.core.CsvHandler.java

/**
 * Apply a big decimal value at the field.
 * /*from w  w  w .  j a  va2 s.co m*/
 * @param value
 *            the value
 * @param formatMask
 *            the decorator mask
 * @param transformMask
 *            the transformation mask
 * @return false if problem otherwise true
 */
protected static String toBigDecimal(final BigDecimal value, final String formatMask,
        final String transformMask) {
    if (value != null) {
        Double dBigDecimal = value.doubleValue();
        if (StringUtils.isNotBlank(transformMask)) {
            // apply transformation mask
            DecimalFormat df = new DecimalFormat(transformMask);
            return df.format(dBigDecimal);

        } else if (StringUtils.isNotBlank(formatMask)) {
            // apply format mask
            DecimalFormat df = new DecimalFormat(formatMask);
            return df.format(dBigDecimal);

        } else {
            return value.toString(); // the exact value
        }
    }
    return StringUtils.EMPTY;
}

From source file:org.jpos.gl.rule.DoubleEntry.java

private void checkEntries(GLTransaction txn, short layer) throws GLException {
    List list = txn.getEntries();
    // if (list.size() < 2) 
    //     throw new GLException ("too few entries (" + list.size() + ")");
    BigDecimal debits = ZERO;
    BigDecimal credits = ZERO;/*  ww  w  .j  a va  2  s .co  m*/
    Iterator iter = list.iterator();

    while (iter.hasNext()) {
        GLEntry entry = (GLEntry) iter.next();
        if (entry.getLayer() == layer) {
            if (entry.isDebit())
                debits = debits.add(entry.getAmount());
            else
                credits = credits.add(entry.getAmount());
        }
    }
    if (!debits.equals(credits)) {
        throw new GLException("Transaction does not balance. debits=" + debits.toString() + ", credits="
                + credits.toString());
    }
}

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

/**
 * Create Facts (the accounting logic) for MMS, MMR.
 * /* w  w w.j  av a2  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 {
            DocLandedCostTemplate newTemplate = (DocLandedCostTemplate) Class.forName(strClassname)
                    .newInstance();
            return newTemplate.createFact(this, as, conn, con, vars);
        } catch (Exception e) {
            log4j.error("Error while creating new instance for DocLandedCostTemplate - " + e);
        }
    }
    C_Currency_ID = as.getC_Currency_ID();
    // 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";
    // Lines
    for (int i = 0; p_lines != null && i < p_lines.length; i++) {
        DocLine_LandedCost line = (DocLine_LandedCost) p_lines[i];

        BigDecimal amount = new BigDecimal(line.getAmount());
        ProductInfo p = new ProductInfo(line.m_M_Product_ID, conn);

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

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

        // If transaction uses Standard Algorithm IPD account will be used, else Asset account
        LCReceiptLineAmt landedCostReceiptLine = OBDal.getInstance().get(LCReceiptLineAmt.class,
                line.m_TrxLine_ID);
        MaterialTransaction transaction = landedCostReceiptLine.getGoodsShipmentLine()
                .getMaterialMgmtMaterialTransactionList().get(0);
        Account account = null;
        if (StringUtils.equals(transaction.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(line, account, line.m_C_Currency_ID, amtCredit, amtDebit, fact_Acct_Group_ID,
                nextSeqNo(SeqNo), DocumentType, line.m_DateAcct, null, conn);

        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, getLandedCostAccount(line.getLandedCostTypeId(), amount, as, conn),
                line.m_C_Currency_ID, amtDebit, amtCredit, fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                line.m_DateAcct, null, conn);

    }

    SeqNo = "0";
    return fact;
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatImportHelper.java

private Object convertNumberTypes(Object val, HCatFieldSchema hfs) {
    HCatFieldSchema.Type hfsType = hfs.getType();

    if (!(val instanceof Number)) {
        return null;
    }//from  w ww. j  av a  2s. co m
    if (val instanceof BigDecimal && hfsType == HCatFieldSchema.Type.STRING
            || hfsType == HCatFieldSchema.Type.VARCHAR || hfsType == HCatFieldSchema.Type.CHAR) {
        BigDecimal bd = (BigDecimal) val;
        String bdStr = null;
        if (bigDecimalFormatString) {
            bdStr = bd.toPlainString();
        } else {
            bdStr = bd.toString();
        }
        if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
            HiveVarchar hvc = new HiveVarchar(bdStr, vti.getLength());
            return hvc;
        } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
            HiveChar hChar = new HiveChar(bdStr, cti.getLength());
            return hChar;
        } else {
            return bdStr;
        }
    }
    Number n = (Number) val;
    if (hfsType == HCatFieldSchema.Type.TINYINT) {
        return n.byteValue();
    } else if (hfsType == HCatFieldSchema.Type.SMALLINT) {
        return n.shortValue();
    } else if (hfsType == HCatFieldSchema.Type.INT) {
        return n.intValue();
    } else if (hfsType == HCatFieldSchema.Type.BIGINT) {
        return n.longValue();
    } else if (hfsType == HCatFieldSchema.Type.FLOAT) {
        return n.floatValue();
    } else if (hfsType == HCatFieldSchema.Type.DOUBLE) {
        return n.doubleValue();
    } else if (hfsType == HCatFieldSchema.Type.BOOLEAN) {
        return n.byteValue() == 0 ? Boolean.FALSE : Boolean.TRUE;
    } else if (hfsType == HCatFieldSchema.Type.STRING) {
        return n.toString();
    } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
        VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
        HiveVarchar hvc = new HiveVarchar(val.toString(), vti.getLength());
        return hvc;
    } else if (hfsType == HCatFieldSchema.Type.CHAR) {
        CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
        HiveChar hChar = new HiveChar(val.toString(), cti.getLength());
        return hChar;
    } else if (hfsType == HCatFieldSchema.Type.DECIMAL) {
        BigDecimal bd = new BigDecimal(n.doubleValue(), MathContext.DECIMAL128);
        return HiveDecimal.create(bd);
    }
    return null;
}

From source file:com.gamethrive.TrackGooglePurchase.java

private void sendPurchases(final ArrayList<String> skusToAdd, final ArrayList<String> newPurchaseTokens) {
    try {/*w w w .  j  a  v a  2s  .  c om*/
        if (getSkuDetailsMethod == null)
            getSkuDetailsMethod = IInAppBillingServiceClass.getMethod("getSkuDetails", int.class, String.class,
                    String.class, Bundle.class);

        Bundle querySkus = new Bundle();
        querySkus.putStringArrayList("ITEM_ID_LIST", skusToAdd);
        Bundle skuDetails = (Bundle) getSkuDetailsMethod.invoke(mIInAppBillingService, 3,
                appContext.getPackageName(), "inapp", querySkus);

        int response = skuDetails.getInt("RESPONSE_CODE");
        if (response == 0) {
            ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
            Map<String, JSONObject> currentSkus = new HashMap<String, JSONObject>();
            JSONObject jsonItem;
            for (String thisResponse : responseList) {
                JSONObject object = new JSONObject(thisResponse);
                String sku = object.getString("productId");
                BigDecimal price = new BigDecimal(object.getString("price_amount_micros"));
                price = price.divide(new BigDecimal(1000000));

                jsonItem = new JSONObject();
                jsonItem.put("sku", sku);
                jsonItem.put("iso", object.getString("price_currency_code"));
                jsonItem.put("amount", price.toString());
                currentSkus.put(sku, jsonItem);
            }

            JSONArray purchasesToReport = new JSONArray();
            for (String sku : skusToAdd) {
                if (!currentSkus.containsKey(sku))
                    continue;
                purchasesToReport.put(currentSkus.get(sku));
            }

            // New purchases to report.
            // Wait until we have a playerID then send purchases to server. If successful then mark them as tracked.
            if (purchasesToReport.length() > 0) {
                final JSONArray finalPurchasesToReport = purchasesToReport;
                gameThrive.idsAvailable(new IdsAvailableHandler() {
                    public void idsAvailable(String playerId, String registrationId) {
                        gameThrive.sendPurchases(finalPurchasesToReport, newAsExisting,
                                new JsonHttpResponseHandler() {
                                    public void onFailure(int statusCode, Header[] headers, Throwable throwable,
                                            JSONObject errorResponse) {
                                        Log.i(GameThrive.TAG, "JSON sendPurchases Failed");
                                        throwable.printStackTrace();
                                        isWaitingForPurchasesRequest = false;
                                    }

                                    public void onSuccess(int statusCode, Header[] headers,
                                            JSONObject response) {
                                        purchaseTokens.addAll(newPurchaseTokens);
                                        prefsEditor.putString("purchaseTokens", purchaseTokens.toString());
                                        prefsEditor.remove("ExistingPurchases");
                                        prefsEditor.commit();
                                        newAsExisting = false;
                                        isWaitingForPurchasesRequest = false;
                                    }
                                });
                    }
                });

            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:org.kuali.kpme.tklm.leave.transfer.validation.BalanceTransferValidationUtils.java

private static boolean validateTransferAmount(BigDecimal transferAmount, AccrualCategory fromCat,
        AccrualCategory toCat, String principalId, LocalDate effectiveDate, AccrualCategoryRule accrualRule) {

    //transfer amount must be less than the max transfer amount defined in the accrual category rule.
    //it cannot be negative.
    boolean isValid = true;

    BigDecimal balance = LmServiceLocator.getAccrualService().getAccruedBalanceForPrincipal(principalId,
            fromCat, effectiveDate);//from   w w w.  j av  a 2 s  .  c om

    BigDecimal maxTransferAmount = null;
    BigDecimal adjustedMaxTransferAmount = null;
    if (ObjectUtils.isNotNull(accrualRule.getMaxTransferAmount())) {
        maxTransferAmount = new BigDecimal(accrualRule.getMaxTransferAmount());
        BigDecimal fullTimeEngagement = HrServiceLocator.getJobService()
                .getFteSumForAllActiveLeaveEligibleJobs(principalId, effectiveDate);
        adjustedMaxTransferAmount = maxTransferAmount.multiply(fullTimeEngagement);
    }

    //use override if one exists.
    EmployeeOverrideContract maxTransferAmountOverride = LmServiceLocator.getEmployeeOverrideService()
            .getEmployeeOverride(principalId, fromCat.getLeavePlan(), fromCat.getAccrualCategory(), "MTA",
                    effectiveDate);
    if (ObjectUtils.isNotNull(maxTransferAmountOverride))
        adjustedMaxTransferAmount = new BigDecimal(maxTransferAmountOverride.getOverrideValue());

    if (ObjectUtils.isNotNull(adjustedMaxTransferAmount)) {
        if (transferAmount.compareTo(adjustedMaxTransferAmount) > 0) {
            isValid &= false;
            String fromUnitOfTime = HrConstants.UNIT_OF_TIME.get(fromCat.getUnitOfTime());
            GlobalVariables.getMessageMap().putError("balanceTransfer.transferAmount",
                    "balanceTransfer.transferAmount.maxTransferAmount", adjustedMaxTransferAmount.toString(),
                    fromUnitOfTime);
        }
    }
    // check for a positive amount.
    if (transferAmount.compareTo(BigDecimal.ZERO) < 0) {
        isValid &= false;
        GlobalVariables.getMessageMap().putError("balanceTransfer.transferAmount",
                "balanceTransfer.transferAmount.negative");
    }

    if (transferAmount.compareTo(balance) > 0) {
        isValid &= false;
        GlobalVariables.getMessageMap().putError("balanceTransfer.transferAmount",
                "maxBalance.amount.exceedsBalance");
    }

    return isValid;
}