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:de.jfachwert.math.PackedDecimal.java

/**
 * Falls man eine {@link BigDecimal} in eine {@link PackedDecimal} wandeln
 * will, kann man diesen Konstruktor hier verwenden. Besser ist es
 * allerdings, wenn man dazu {@link #valueOf(BigDecimal)} verwendet.
 *
 * @param zahl eine Dezimalzahl/*from w  w w . jav a 2s  .  com*/
 */
public PackedDecimal(BigDecimal zahl) {
    this(zahl.toString());
}

From source file:org.mobicents.servlet.restcomm.http.converter.AbstractConverter.java

protected void writePrice(final BigDecimal price, final HierarchicalStreamWriter writer) {
    writer.startNode("Price");
    writer.setValue(price.toString());
    writer.endNode();//from www  .  j  a v a 2s. co m
}

From source file:org.researchgraph.crosswalk.CrosswalkRG.java

private boolean processDataset(final Dataset dataset, final Graph graph, boolean deleted) {
    ++existingRecords;/*from   ww  w.  j  ava 2s.  c  om*/

    if (verbose)
        System.out.println("Processing Dataset");

    String key = dataset.getKey();
    if (StringUtils.isEmpty(key)) {
        return false;
    }

    if (verbose)
        System.out.println("Key: " + key);

    String source = dataset.getSource();
    if (StringUtils.isEmpty(source))
        source = this.source;

    GraphNode node = GraphNode.builder().withKey(new GraphKey(source, key)).withNodeSource(source)
            .withNodeType(GraphUtils.TYPE_DATASET).withLabel(this.source).withLabel(GraphUtils.TYPE_DATASET)
            .build();

    if (deleted) {
        node.setDeleted(true);
        graph.addNode(node);

        ++deletedRecords;

        return true;
    }

    String localId = dataset.getLocalId();
    if (!StringUtils.isEmpty(localId))
        node.setProperty(GraphUtils.PROPERTY_LOCAL_ID, localId);

    XMLGregorianCalendar lastUpdated = dataset.getLastUpdated();
    if (null != lastUpdated) {
        String lastUpdatedString = formatter.format(lastUpdated.toGregorianCalendar().getTime());
        if (!StringUtils.isEmpty(lastUpdatedString))
            node.setProperty(GraphUtils.PROPERTY_LAST_UPDATED, lastUpdatedString);
    }

    String url = GraphUtils.extractFormalizedUrl(dataset.getUrl());
    if (!StringUtils.isEmpty(url))
        node.setProperty(GraphUtils.PROPERTY_URL, url);

    String title = dataset.getTitle();
    if (!StringUtils.isEmpty(title))
        node.setProperty(GraphUtils.PROPERTY_TITLE, title);

    String doi = GraphUtils.extractDoi(dataset.getDoi());
    if (!StringUtils.isEmpty(doi))
        node.setProperty(GraphUtils.PROPERTY_DOI, doi);

    XMLGregorianCalendar publicationYear = dataset.getPublicationYear();
    if (null != publicationYear && publicationYear.getYear() > 0)
        node.setProperty(GraphUtils.PROPERTY_PUBLICATION_YEAR, publicationYear.getYear());

    String license = GraphUtils.extractFormalizedUrl(dataset.getLicense());
    if (!StringUtils.isEmpty(license))
        node.setProperty(GraphUtils.PROPERTY_LICENSE, license);

    BigDecimal megabyte = dataset.getMegabyte();
    if (null != megabyte)
        node.setProperty(GraphUtils.PROPERTY_MEGABYTE, megabyte.toString());

    graph.addNode(node);

    return true;
}

From source file:org.pentaho.di.trans.steps.pgbulkloader.PGBulkLoader.java

private void writeRowToPostgres(RowMetaInterface rowMeta, Object[] r) throws KettleException {

    try {/*from  ww w .  ja  v  a 2  s. c o  m*/
        // So, we have this output stream to which we can write CSV data to.
        // Basically, what we need to do is write the binary data (from strings to it as part of this proof of concept)
        //
        // Let's assume the data is in the correct format here too.
        //
        for (int i = 0; i < data.keynrs.length; i++) {
            if (i > 0) {
                // Write a separator
                //
                data.pgOutputStream.write(data.separator);
            }

            int index = data.keynrs[i];
            ValueMetaInterface valueMeta = rowMeta.getValueMeta(index);
            Object valueData = r[index];

            if (valueData != null) {
                switch (valueMeta.getType()) {
                case ValueMetaInterface.TYPE_STRING:
                    data.pgOutputStream.write(data.quote);

                    // No longer dump the bytes for a Lazy Conversion;
                    // We need to escape the quote characters in every string
                    String quoteStr = new String(data.quote);
                    String escapedString = valueMeta.getString(valueData).replace(quoteStr,
                            quoteStr + quoteStr);
                    data.pgOutputStream.write(escapedString.getBytes());

                    data.pgOutputStream.write(data.quote);
                    break;
                case ValueMetaInterface.TYPE_INTEGER:
                    if (valueMeta.isStorageBinaryString()) {
                        data.pgOutputStream.write((byte[]) valueData);
                    } else {
                        data.pgOutputStream.write(Long.toString(valueMeta.getInteger(valueData)).getBytes());
                    }
                    break;
                case ValueMetaInterface.TYPE_DATE:
                    // Format the date in the right format.
                    //
                    switch (data.dateFormatChoices[i]) {
                    // Pass the data along in the format chosen by the user OR in binary format...
                    //
                    case PGBulkLoaderMeta.NR_DATE_MASK_PASS_THROUGH:
                        if (valueMeta.isStorageBinaryString()) {
                            data.pgOutputStream.write((byte[]) valueData);
                        } else {
                            String dateString = valueMeta.getString(valueData);
                            if (dateString != null) {
                                data.pgOutputStream.write(dateString.getBytes());
                            }
                        }
                        break;

                    // Convert to a "YYYY/MM/DD" format
                    //
                    case PGBulkLoaderMeta.NR_DATE_MASK_DATE:
                        String dateString = data.dateMeta.getString(valueMeta.getDate(valueData));
                        if (dateString != null) {
                            data.pgOutputStream.write(dateString.getBytes());
                        }
                        break;

                    // Convert to a "YYYY/MM/DD HH:MM:SS" (ISO) format
                    //
                    case PGBulkLoaderMeta.NR_DATE_MASK_DATETIME:
                        String dateTimeString = data.dateTimeMeta.getString(valueMeta.getDate(valueData));
                        if (dateTimeString != null) {
                            data.pgOutputStream.write(dateTimeString.getBytes());
                        }
                        break;

                    default:
                        break;
                    }
                    break;
                case ValueMetaInterface.TYPE_BOOLEAN:
                    if (valueMeta.isStorageBinaryString()) {
                        data.pgOutputStream.write((byte[]) valueData);
                    } else {
                        data.pgOutputStream.write(Double.toString(valueMeta.getNumber(valueData)).getBytes());
                    }
                    break;
                case ValueMetaInterface.TYPE_NUMBER:
                    if (valueMeta.isStorageBinaryString()) {
                        data.pgOutputStream.write((byte[]) valueData);
                    } else {
                        data.pgOutputStream.write(Double.toString(valueMeta.getNumber(valueData)).getBytes());
                    }
                    break;
                case ValueMetaInterface.TYPE_BIGNUMBER:
                    if (valueMeta.isStorageBinaryString()) {
                        data.pgOutputStream.write((byte[]) valueData);
                    } else {
                        BigDecimal big = valueMeta.getBigNumber(valueData);
                        if (big != null) {
                            data.pgOutputStream.write(big.toString().getBytes());
                        }
                    }
                    break;
                default:
                    break;
                }
            }
        }

        // Now write a newline
        //
        data.pgOutputStream.write(data.newline);
    } catch (Exception e) {
        throw new KettleException("Error serializing rows of data to the psql command", e);
    }

}

From source file:com.salesmanager.core.module.impl.application.shipping.CalculateBoxPackingModule.java

public void storeConfiguration(int merchantId, ConfigurationResponse vo, HttpServletRequest request)
        throws Exception {

    // get the store information
    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore store = mservice.getMerchantStore(merchantId);

    // id - merchantId - SHP_PACK - packing-item/packing/box - [values] -
    // null - packing-item/packing/box

    // validate submited values
    // box_maxweight
    // box_weight
    // box_length
    // box_height
    // box_width/*from   w w  w.j a  va 2  s .  co m*/

    Locale locale = LocaleUtil.getLocale(request);

    StringBuffer buf = new StringBuffer();

    try {
        BigDecimal width = CurrencyUtil.validateMeasure(request.getParameter("box_width"), store.getCurrency());
        // int width = Integer.parseInt();
        buf.append(width.toString()).append("|");
    } catch (Exception e) {
        throw new ValidationException(LabelUtil.getInstance().getText(locale, "module.box.invalid.width"));
    }

    try {
        BigDecimal height = CurrencyUtil.validateMeasure(request.getParameter("box_height"),
                store.getCurrency());
        // int height =
        // Integer.parseInt(request.getParameter("box_height"));
        buf.append(height.toString()).append("|");
    } catch (Exception e) {
        throw new ValidationException(LabelUtil.getInstance().getText(locale, "module.box.invalid.height"));
    }

    try {
        BigDecimal length = CurrencyUtil.validateMeasure(request.getParameter("box_length"),
                store.getCurrency());
        // int length =
        // Integer.parseInt(request.getParameter("box_length"));
        buf.append(length.toString()).append("|");
    } catch (Exception e) {
        throw new ValidationException(LabelUtil.getInstance().getText(locale, "module.box.invalid.length"));
    }

    try {
        BigDecimal weight = CurrencyUtil.validateMeasure(request.getParameter("box_weight"),
                store.getCurrency());

        buf.append(weight.toString()).append("|");
    } catch (Exception e) {
        throw new ValidationException(LabelUtil.getInstance().getText(locale, "module.box.invalid.weight"));
    }

    try {
        BigDecimal maxweight = CurrencyUtil.validateMeasure(request.getParameter("box_maxweight"),
                store.getCurrency());

        buf.append(maxweight.toString()).append("|");
    } catch (Exception e) {
        throw new ValidationException(LabelUtil.getInstance().getText(locale, "module.box.invalid.maxweight"));
    }

    try {
        int treshold = Integer.parseInt(request.getParameter("box_treshold"));
        buf.append(treshold);
    } catch (Exception e) {
        throw new ValidationException(LabelUtil.getInstance().getText(locale, "module.box.invalid.treshold"));
    }

    ConfigurationRequest vr = new ConfigurationRequest(merchantId, "SHP_PACK");
    ConfigurationResponse resp = mservice.getConfiguration(vr);

    MerchantConfiguration conf = null;
    if (resp == null || resp.getMerchantConfiguration("SHP_PACK") == null) {

        conf = new MerchantConfiguration();

    } else {
        conf = resp.getMerchantConfiguration("SHP_PACK");
    }

    conf.setMerchantId(merchantId);
    conf.setConfigurationKey("SHP_PACK");
    conf.setConfigurationValue("packing-box");
    conf.setConfigurationValue1(buf.toString());

    mservice.saveOrUpdateMerchantConfiguration(conf);

}

From source file:net.groupbuy.plugin.paypal.PaypalController.java

/**
 * /*from  w ww  .  j a va2  s  .co  m*/
 */
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(String paymentName, String partner, Currency currency, FeeType feeType, BigDecimal fee,
        String logo, String description, @RequestParam(defaultValue = "false") Boolean isEnabled, Integer order,
        RedirectAttributes redirectAttributes) {
    PluginConfig pluginConfig = paypalPlugin.getPluginConfig();
    pluginConfig.setAttribute(PaymentPlugin.PAYMENT_NAME_ATTRIBUTE_NAME, paymentName);
    pluginConfig.setAttribute("partner", partner);
    pluginConfig.setAttribute("currency", currency.toString());
    pluginConfig.setAttribute(PaymentPlugin.FEE_TYPE_ATTRIBUTE_NAME, feeType.toString());
    pluginConfig.setAttribute(PaymentPlugin.FEE_ATTRIBUTE_NAME, fee.toString());
    pluginConfig.setAttribute(PaymentPlugin.LOGO_ATTRIBUTE_NAME, logo);
    pluginConfig.setAttribute(PaymentPlugin.DESCRIPTION_ATTRIBUTE_NAME, description);
    pluginConfig.setIsEnabled(isEnabled);
    pluginConfig.setOrder(order);
    pluginConfigService.update(pluginConfig);
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:/admin/payment_plugin/list.jhtml";
}

From source file:se.frikod.payday.DailyBudgetFragment.java

public void editBudgetItem(final View v, final int currentIndex) {

    LayoutInflater inflater = activity.getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.daily_budget_edit_budget_item, null);

    AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
    builder.setTitle(getString(R.string.edit_budget_item_title));

    final BudgetItem budgetItem;
    final EditText titleView = (EditText) dialogView.findViewById(R.id.budget_item_title);
    final Spinner typeView = (Spinner) dialogView.findViewById(R.id.budget_item_type);
    final EditText amountView = (EditText) dialogView.findViewById(R.id.budget_item_amount);

    if (currentIndex == NEW_BUDGET_ITEM) {
        budgetItem = null;//from  w ww  . j ava2s.  c  o  m
        builder.setTitle(getString(R.string.add_budget_item_dialog_title));
        builder.setPositiveButton(R.string.add_budget_item, null);
    } else {
        builder.setTitle(getString(R.string.edit_budget_item_title));

        budgetItem = budget.budgetItems.get(currentIndex);

        String title = budgetItem.title;
        BigDecimal amount = budgetItem.amount;
        int type;
        if (amount.signum() < 0) {
            type = 0;
            amount = amount.negate();
        } else {
            type = 1;
        }

        titleView.setText(title);
        typeView.setSelection(type);
        amountView.setText(amount.toString());

        builder.setNeutralButton(getString(R.string.delete_budget_item_yes),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
                        vibrator.vibrate(100);
                        budget.budgetItems.remove(currentIndex);
                        budget.saveBudgetItems();
                        updateBudgetItems();
                        dialog.dismiss();
                    }

                });
        builder.setPositiveButton(R.string.update_budget_item, null);
    }

    builder.setNegativeButton(getString(R.string.delete_budget_item_no), new DialogInterface.OnClickListener() {

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

    /* onClick listener for update needs to be setup like this to
       prevent closing dialog on error
     */

    final AlertDialog d = builder.create();
    d.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {
            Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
            assert b != null;
            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    BigDecimal amount;
                    try {
                        amount = new BigDecimal(amountView.getText().toString());
                        if (typeView.getSelectedItemId() == 0)
                            amount = amount.negate();
                    } catch (NumberFormatException e) {

                        Toast.makeText(activity.getApplicationContext(),
                                getString(R.string.new_budget_item_no_amount_specified), Toast.LENGTH_SHORT)
                                .show();

                        return;
                    }

                    String title = titleView.getText().toString();

                    if (budgetItem != null) {
                        budgetItem.amount = amount;
                        budgetItem.title = title;
                    } else {
                        budget.budgetItems.add(new BudgetItem(title, amount));
                    }

                    budget.saveBudgetItems();
                    updateBudgetItems();
                    d.dismiss();
                }
            });
        }
    });

    d.setView(dialogView);
    d.show();
}

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

protected boolean validateDutyListPercentage(PositionBo aPosition) {
    if (CollectionUtils.isNotEmpty(aPosition.getDutyList())) {
        BigDecimal sum = BigDecimal.ZERO;
        for (PositionDutyBo aDuty : aPosition.getDutyList()) {
            if (aDuty != null && aDuty.getPercentage() != null) {
                sum = sum.add(aDuty.getPercentage());
            }/*  w  w  w  .  ja  v  a2  s  .  c  o m*/
        }
        if (sum.compareTo(new BigDecimal(100)) > 0) {
            String[] parameters = new String[1];
            parameters[0] = sum.toString();
            this.putFieldError("dataObject.dutyList", "duty.percentage.exceedsMaximum", parameters);
            return false;
        }
    }
    return true;
}

From source file:uk.ac.leeds.ccg.andyt.projects.moses.process.Comparison.java

public void compareCASUV003WithCAS001() throws Exception {
    File infile;// ww w. j  a v a2s .co  m
    infile = new File("C:/Work/Projects/MoSeS/Workspace/UV003.dat");
    CASUV003DataHandler cASUV003DataHandler = new CASUV003DataHandler(infile);
    infile = new File("C:/Work/Projects/MoSeS/Workspace/CAS001.dat");
    CAS001DataHandler tCAS001DataHandler = new CAS001DataHandler(infile);

    CASUV003DataRecord aCASUV003DataRecord;
    CAS001DataRecord aCAS001DataRecord;
    long difference;
    long maxDifference = Long.MIN_VALUE;
    long sumOfSquaredDifference = 0L;
    long totalDifference = 0L;
    long absoluteDifference = 0L;
    long totalAbsoluteDifference = 0L;
    long RecordID;
    long nRecords = cASUV003DataHandler.getNDataRecords();
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        difference = (long) (aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        if (difference < 0) {
            absoluteDifference = difference * -1L;
        }
        sumOfSquaredDifference += (difference * difference);
        maxDifference = Math.max(maxDifference, difference);
        totalDifference += difference;
        totalAbsoluteDifference += absoluteDifference;
    }
    int scale = 100;
    int roundingMode = BigDecimal.ROUND_HALF_EVEN;
    BigDecimal nRecordsBigDecimal = new BigDecimal(nRecords);
    BigDecimal meanDifferenceBigDecimal = new BigDecimal(maxDifference).divide(nRecordsBigDecimal, scale,
            roundingMode);
    System.out.println("nRecords " + nRecords);
    System.out.println("meanDifferenceBigDecimal " + meanDifferenceBigDecimal.toString());
    System.out.println("sumOfSquaredDifference " + sumOfSquaredDifference);
    System.out.println("maxDifference " + maxDifference);
    System.out.println("totalAbsoluteDifference " + totalAbsoluteDifference);
    System.out.println("totalDifference " + totalDifference);
    BigDecimal standardDeviationOfDifferenceBigDecimal = new BigDecimal("0");
    BigDecimal differenceBigDecimal;
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        differenceBigDecimal = new BigDecimal(
                aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        standardDeviationOfDifferenceBigDecimal = differenceBigDecimal.multiply(differenceBigDecimal);
    }
    standardDeviationOfDifferenceBigDecimal = standardDeviationOfDifferenceBigDecimal
            .divide(nRecordsBigDecimal.subtract(BigDecimal.ONE), scale, roundingMode);
    standardDeviationOfDifferenceBigDecimal = Generic_BigDecimal.sqrt(standardDeviationOfDifferenceBigDecimal,
            scale, RoundingMode.HALF_EVEN);
    System.out.println("standardDeviationOfDifferenceBigDecimal " + standardDeviationOfDifferenceBigDecimal);
}

From source file:org.egov.ptis.actions.recovery.RecoveryAction.java

@ValidationErrorPage(value = "notice159View")
public String generateCeaseNotice() {
    LOGGER.debug("RecoveryAction | generateCeaseNotice | Start" + recovery.getCeaseNotice());
    String noticeNo = propertyTaxNumberGenerator.generateRecoveryNotice(PropertyTaxConstants.NOTICE159);
    recovery.getBasicProperty()//from  w  ww.  j  a va 2  s  .  c o  m
            .setStatus(getPropStatusByStatusCode(PropertyTaxConstants.RECOVERY_CEASENOTICEISSUED));
    recovery.setStatus(getEgwStatusForModuleAndCode(PropertyTaxConstants.RECOVERY_MODULE,
            PropertyTaxConstants.RECOVERY_CEASENOTICEISSUED));
    // FIX ME
    // Position position =
    // eisCommonsManager.getPositionByUserId(Integer.valueOf(ApplicationThreadLocals.getUserId()));
    Position position = null;
    recovery.transition().progress().withNextAction("END").withStateValue("END").withOwner(position)
            .withComments(workflowBean.getComments());

    Map<String, Object> paramMap = getNotice159Param(recovery);
    PropertyTaxUtil propertyTaxUtil = new PropertyTaxUtil();
    Map<String, Map<String, BigDecimal>> reasonwiseDues = propertyTaxUtil
            .getDemandDues(recovery.getBasicProperty().getUpicNo());
    PropertyBillInfo propertyBillInfo = new PropertyBillInfo(reasonwiseDues, recovery.getBasicProperty(), null);
    BigDecimal totalRecoverAmt = propertyBillInfo.getGrandTotal()
            .add(BigDecimal.valueOf(Double.valueOf(paramMap.get("totalWarrantFees").toString()))).setScale(2);
    paramMap.put("totalRecoverAmt", totalRecoverAmt.toString());
    paramMap.put("executionDate", DDMMYYYYFORMATS.format(recovery.getCeaseNotice().getExecutionDate()));
    paramMap.put("currentDate", DDMMYYYYFORMATS.format(new Date()));
    paramMap.put("north", recovery.getBasicProperty().getPropertyID().getNorthBoundary());
    paramMap.put("south", recovery.getBasicProperty().getPropertyID().getSouthBoundary());
    paramMap.put("zoneNum", recovery.getBasicProperty().getPropertyID().getZone().getBoundaryNum().toString());
    paramMap.put("east", recovery.getBasicProperty().getPropertyID().getEastBoundary());
    paramMap.put("west", recovery.getBasicProperty().getPropertyID().getWestBoundary());
    ReportRequest reportRequest = new ReportRequest("Notice-159", propertyBillInfo, paramMap);
    reportRequest.setPrintDialogOnOpenReport(true);
    ReportOutput reportOutput = reportService.createReport(reportRequest);
    reportId = addingReportToSession(reportOutput);
    if (reportOutput != null && reportOutput.getReportOutputData() != null) {
        InputStream Notice159PDF = new ByteArrayInputStream(reportOutput.getReportOutputData());
        PtNotice ptNotice = noticeService.saveNotice(null, noticeNo, PropertyTaxConstants.NOTICE159,
                recovery.getBasicProperty(), Notice159PDF);
        recovery.getCeaseNotice().setNotice(ptNotice);
    }
    LOGGER.debug("RecoveryAction | generateCeaseNotice | End" + recovery.getCeaseNotice());
    return PRINT;
}