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:com.prowidesoftware.swift.utils.SwiftFormatUtils.java

/**
 * Return the number of decimals for the given number, which can be <code>null</code>, in which case this method returns zero.
 * //from  ww  w  . j  a  v  a 2 s .  c o m
 * @return the number of decimal in the number or zero if there are none or the amount is <code>null</code>
 * @since 7.8
 */
public static int decimalsInAmount(final BigDecimal amount) {
    if (amount != null) {
        BigDecimal d = new BigDecimal(amount.toString());
        BigDecimal result = d.subtract(d.setScale(0, RoundingMode.FLOOR)).movePointRight(d.scale());
        if (result.intValue() != 0) {
            return result.toString().length();
        }
    }
    return 0;
}

From source file:com.aegiswallet.utils.WalletUtils.java

public static String getExchangeRateWithSymbol(Context context, SharedPreferences prefs) {
    File file = context.getApplicationContext().getFileStreamPath(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME);
    if (file.exists()) {
        JSONObject jsonObject = BasicUtils.parseJSONData(context, Constants.BLOCKCHAIN_CURRENCY_FILE_NAME);
        try {//ww w . j  a  v a 2 s .  c om
            if (jsonObject != null) {

                JSONObject newObject = jsonObject
                        .getJSONObject(prefs.getString(Constants.CURRENCY_PREF_KEY, null));
                double doubleValue = newObject.getDouble("last");

                BigDecimal bigDecimal = BigDecimal.valueOf(doubleValue);
                return newObject.getString("symbol") + bigDecimal.toString();
            }
        } catch (JSONException e) {
            Log.e("Wallet Utils", "JSON Exception " + e.getMessage());
        }
    }

    return null;
}

From source file:org.kalypso.ui.wizards.results.ResultSldHelper.java

private static String processVectorStyle(final BigDecimal maxValue, final URL url, final String type) {
    InputStream is = null;/*from w  w  w .j  a v a 2  s  .  co m*/
    try {
        if (NodeResultHelper.VELO_TYPE.equals(type) || NodeResultHelper.WAVE_DIRECTION_TYPE.equals(type)) {
            is = new BufferedInputStream(url.openStream());
        } else {
            final URL extUrl = ResultSldHelper.class.getResource("resources/myDefaultNodeExt.sld"); //$NON-NLS-1$
            is = new BufferedInputStream(extUrl.openStream());
        }
        String fileString = IOUtils.toString(is, "UTF-8"); //$NON-NLS-1$
        is.close();

        // we assume, that the mean distance of mesh nodes is about 30 m, so that the vectors are expanded by an factor
        // which delivers vector lengths of 30 m as maximum.
        BigDecimal factorValue;
        if (maxValue != null && maxValue.doubleValue() > 0)
            factorValue = new BigDecimal(30 / maxValue.doubleValue()).setScale(0, BigDecimal.ROUND_CEILING);
        else
            factorValue = new BigDecimal(100).setScale(0, BigDecimal.ROUND_CEILING);

        String factor = factorValue.toString();
        if (NodeResultHelper.VELO_TYPE.equals(type)) {
            return fileString.replaceAll(NodeResultHelper.VECTORFACTOR, factor)
                    .replaceAll(NodeResultHelper.SIZE_NORM_NODE_FUNC, "velocityNorm"); //$NON-NLS-1$
        } else if (NodeResultHelper.WAVE_DIRECTION_TYPE.equals(type)) {
            return fileString.replaceAll(NodeResultHelper.VECTORFACTOR, factor)
                    .replaceAll(NodeResultHelper.SIZE_NORM_NODE_FUNC, "wavehsig") //$NON-NLS-1$
                    .replaceAll("velocityRotation", type.toLowerCase()); //$NON-NLS-1$ 
        } else {
            if (factorValue.doubleValue() > 30) {
                factor = "10"; //$NON-NLS-1$ 
            }
            return fileString.replaceAll(NodeResultHelper.VECTORFACTOR, factor)
                    .replaceAll(NodeResultHelper.NODESTYLE_TEMPLATE, type.toLowerCase());
        }

    } catch (final IOException e) {
        e.printStackTrace();

    } finally {
        IOUtils.closeQuietly(is);
    }
    return null;

}

From source file:com.wms.utils.DataUtil.java

public static boolean isLongNumber(BigDecimal minCar) {
    try {//from  w w w  . j a va2  s.  c  om
        Long.parseLong(minCar.toString());
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:com.coinblesk.client.utils.UIUtils.java

public static String getSum(String amounts) {
    String delims = "[+]";
    String result = "0";
    String[] tokens = amounts.split(delims);
    if (tokens.length > 1) {
        BigDecimal sum = new BigDecimal(0);
        for (int i = 0; i < tokens.length; i++) {
            sum = sum.add(new BigDecimal(tokens[i]));
        }//from w ww  . ja v  a 2  s .c  o m
        result = sum.toString();
    }
    return result;
}

From source file:org.openbravo.materialmgmt.ReservationUtils.java

/**
 * Function to reserve in allocated or not allocated given stock or purchase order line. Available
 * OBObject are:<br>/* w w w.j  a v  a2 s  .  com*/
 * - StorageDetail: reserves stock in the warehouse.<br>
 * - OrderLine: reserves stock pending to receipt purchase order line.
 */

public static ReservationStock reserveStockManual(Reservation reservation, BaseOBObject obObject,
        BigDecimal quantity, String allocated) throws OBException {

    String strType = "";

    if (obObject instanceof OrderLine) {
        strType = "PO";
    } else if (obObject instanceof StorageDetail) {
        strType = "SD";
    } else {
        throw new OBException("notValidReservationType");
    }

    OBDal.getInstance().flush();
    CSResponse cs = null;
    try {
        cs = ReservationUtilsData.reserveStockManual(OBDal.getInstance().getConnection(false),
                new DalConnectionProvider(false), reservation.getId(), strType, obObject.getId().toString(),
                quantity.toString(), (String) DalUtil.getId(OBContext.getOBContext().getUser()), allocated);
    } catch (ServletException e) {
        String message = OBMessageUtils.translateError(e.getMessage()).getMessage();
        throw new OBException(message, e);
    }

    if (cs != null && cs.returnValue != null) {
        return OBDal.getInstance().get(ReservationStock.class, cs.returnValue);
    }

    return null;
}

From source file:com.salesmanager.core.util.CurrencyUtil.java

public static String displayFormatedAmountWithCurrency(BigDecimal amount, String currencycode) {

    try {// www. j  a  va 2 s . co m

        if (currencycode == null) {
            currencycode = getDefaultCurrency();
        }

        CurrencyModule module = (CurrencyModule) currencyMap.get(currencycode);

        if (module == null) {
            log.error("There is no CurrencyModule defined for currency " + currencycode
                    + " in module/impl/application/currencies");
            return amount.toString();
        }

        return module.getFormatedAmountWithCurrency(amount);

    } catch (Exception e) {
        log.error("Cannot format amount " + amount.toString() + " for currency " + currencycode);
        return amount.toString();
    }
}

From source file:com.salesmanager.core.util.CurrencyUtil.java

public static String displayFormatedCssAmountWithCurrency(BigDecimal amount, String currencycode) {

    try {/*www.  j a  v a 2  s. co  m*/

        if (currencycode == null) {
            currencycode = getDefaultCurrency();
        }

        CurrencyModule module = (CurrencyModule) currencyMap.get(currencycode);

        if (module == null) {
            log.error("There is no CurrencyModule defined for currency " + currencycode
                    + " in module/impl/application/currencies");
            return amount.toString();
        }

        return module.getFormatedAmountWithCurrency(amount, "product-value");

    } catch (Exception e) {
        log.error("Cannot format amount " + amount.toString() + " for currency " + currencycode);
        return amount.toString();
    }
}

From source file:org.eclipselabs.garbagecat.Main.java

/**
 * Create Garbage Collection Analysis report.
 * /*from   w  ww . j  a  v a2 s .c o m*/
 * TODO: Move to JvmRun to facilitate testing.
 * 
 * @param jvmRun
 *            JVM run data.
 * @param reportFileName
 *            Report file name.
 * @param version
 *            Whether or not to report garbagecat version.
 * @param latestVersion
 *            Whether or not to report latest garbagecat version.
 * 
 */
public static void createReport(JvmRun jvmRun, String reportFileName, boolean version, boolean latestVersion) {
    File reportFile = new File(reportFileName);
    FileWriter fileWriter = null;
    BufferedWriter bufferedWriter = null;
    try {
        fileWriter = new FileWriter(reportFile);
        bufferedWriter = new BufferedWriter(fileWriter);

        if (version || latestVersion) {
            bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR);
            if (version) {
                bufferedWriter.write(
                        "Running garbagecat version: " + getVersion() + System.getProperty("line.separator"));
            }
            if (latestVersion) {
                bufferedWriter.write("Latest garbagecat version/tag: " + getLatestVersion()
                        + System.getProperty("line.separator"));
            }
        }

        // Bottlenecks
        List<String> bottlenecks = jvmRun.getBottlenecks();
        if (bottlenecks.size() > 0) {
            bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR);
            bufferedWriter.write(
                    "Throughput less than " + jvmRun.getThroughputThreshold() + "%" + Constants.LINE_SEPARATOR);
            bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);
            Iterator<String> iterator = bottlenecks.iterator();
            while (iterator.hasNext()) {
                bufferedWriter.write(iterator.next() + Constants.LINE_SEPARATOR);
            }
        }

        // JVM information
        if (jvmRun.getJvm().getVersion() != null || jvmRun.getJvm().getOptions() != null
                || jvmRun.getJvm().getMemory() != null) {
            bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR);
            bufferedWriter.write("JVM:" + Constants.LINE_SEPARATOR);
            bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);
            if (jvmRun.getJvm().getVersion() != null) {
                bufferedWriter.write("Version: " + jvmRun.getJvm().getVersion() + Constants.LINE_SEPARATOR);
            }
            if (jvmRun.getJvm().getOptions() != null) {
                bufferedWriter.write("Options: " + jvmRun.getJvm().getOptions() + Constants.LINE_SEPARATOR);
            }
            if (jvmRun.getJvm().getMemory() != null) {
                bufferedWriter.write("Memory: " + jvmRun.getJvm().getMemory() + Constants.LINE_SEPARATOR);
            }
        }

        // Summary
        bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR);
        bufferedWriter.write("SUMMARY:" + Constants.LINE_SEPARATOR);
        bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);

        // GC stats
        bufferedWriter.write("# GC Events: " + jvmRun.getBlockingEventCount() + Constants.LINE_SEPARATOR);
        if (jvmRun.getBlockingEventCount() > 0) {
            bufferedWriter.write("Event Types: ");
            List<LogEventType> eventTypes = jvmRun.getEventTypes();
            Iterator<LogEventType> iterator = eventTypes.iterator();
            boolean firstEvent = true;
            while (iterator.hasNext()) {
                LogEventType eventType = iterator.next();
                // Only report GC events
                if (JdkUtil.isReportable(eventType)) {
                    if (!firstEvent) {
                        bufferedWriter.write(", ");
                    }
                    bufferedWriter.write(eventType.toString());
                    firstEvent = false;
                }
            }
            bufferedWriter.write(Constants.LINE_SEPARATOR);
            // Inverted parallelism. Only report if we have Serial/Parallel/CMS/G1 events.
            if (jvmRun.getCollectorFamilies() != null && jvmRun.getCollectorFamilies().size() > 0) {
                bufferedWriter
                        .write("# Parallel Events: " + jvmRun.getParallelCount() + Constants.LINE_SEPARATOR);
                bufferedWriter.write("# Inverted Parallelism: " + jvmRun.getInvertedParallelismCount()
                        + Constants.LINE_SEPARATOR);
                if (jvmRun.getInvertedParallelismCount() > 0) {
                    bufferedWriter.write("Max Inverted Parallelism: "
                            + jvmRun.getWorstInvertedParallelismEvent().getLogEntry()
                            + Constants.LINE_SEPARATOR);
                }
            }
            // NewRatio
            if (jvmRun.getMaxYoungSpace() > 0 && jvmRun.getMaxOldSpace() > 0) {
                bufferedWriter.write("NewRatio: " + jvmRun.getNewRatio() + Constants.LINE_SEPARATOR);
            }
            // Max heap occupancy.
            bufferedWriter.write(
                    "Max Heap Occupancy: " + jvmRun.getMaxHeapOccupancy() + "K" + Constants.LINE_SEPARATOR);
            // Max heap space.
            bufferedWriter
                    .write("Max Heap Space: " + jvmRun.getMaxHeapSpace() + "K" + Constants.LINE_SEPARATOR);
            if (jvmRun.getMaxPermSpace() > 0) {
                // Max perm occupancy.
                bufferedWriter.write("Max Perm/Metaspace Occupancy: " + jvmRun.getMaxPermOccupancy() + "K"
                        + Constants.LINE_SEPARATOR);
                // Max perm space.
                bufferedWriter.write("Max Perm/Metaspace Space: " + jvmRun.getMaxPermSpace() + "K"
                        + Constants.LINE_SEPARATOR);
            }
            // GC throughput
            bufferedWriter.write("GC Throughput: ");
            if (jvmRun.getGcThroughput() == 100 && jvmRun.getBlockingEventCount() > 0) {
                // Provide clue it's rounded to 100
                bufferedWriter.write("~");
            }
            bufferedWriter.write(jvmRun.getGcThroughput() + "%" + Constants.LINE_SEPARATOR);
            // GC max pause
            BigDecimal maxGcPause = JdkMath.convertMillisToSecs(jvmRun.getMaxGcPause());
            bufferedWriter.write("GC Max Pause: " + maxGcPause.toString() + " secs" + Constants.LINE_SEPARATOR);
            // GC total pause time
            BigDecimal totalGcPause = JdkMath.convertMillisToSecs(jvmRun.getTotalGcPause());
            bufferedWriter
                    .write("GC Total Pause: " + totalGcPause.toString() + " secs" + Constants.LINE_SEPARATOR);
        }
        if (jvmRun.getStoppedTimeEventCount() > 0) {
            // Stopped time throughput
            bufferedWriter.write("Stopped Time Throughput: ");
            if (jvmRun.getStoppedTimeThroughput() == 100 && jvmRun.getStoppedTimeEventCount() > 0) {
                // Provide clue it's rounded to 100
                bufferedWriter.write("~");
            }
            bufferedWriter.write(jvmRun.getStoppedTimeThroughput() + "%" + Constants.LINE_SEPARATOR);
            // Max stopped time
            BigDecimal maxStoppedPause = JdkMath.convertMillisToSecs(jvmRun.getMaxStoppedTime());
            bufferedWriter.write("Stopped Time Max Pause: " + maxStoppedPause.toString() + " secs"
                    + Constants.LINE_SEPARATOR);
            // Total stopped time
            BigDecimal totalStoppedTime = JdkMath.convertMillisToSecs(jvmRun.getTotalStoppedTime());
            bufferedWriter.write(
                    "Stopped Time Total: " + totalStoppedTime.toString() + " secs" + Constants.LINE_SEPARATOR);
            // Ratio of GC vs. stopped time. 100 means all stopped time due to GC.
            if (jvmRun.getBlockingEventCount() > 0) {
                bufferedWriter.write(
                        "GC/Stopped Ratio: " + jvmRun.getGcStoppedRatio() + "%" + Constants.LINE_SEPARATOR);
            }
        }
        // First/last timestamps
        if (jvmRun.getBlockingEventCount() > 0 || jvmRun.getStoppedTimeEventCount() > 0) {
            // First event
            String firstEventDatestamp = JdkUtil.getDateStamp(jvmRun.getFirstEvent().getLogEntry());
            if (firstEventDatestamp != null) {
                bufferedWriter.write("First Datestamp: ");
                bufferedWriter.write(firstEventDatestamp);
                bufferedWriter.write(Constants.LINE_SEPARATOR);
            }
            bufferedWriter.write("First Timestamp: ");
            BigDecimal firstEventTimestamp = JdkMath.convertMillisToSecs(jvmRun.getFirstEvent().getTimestamp());
            bufferedWriter.write(firstEventTimestamp.toString());
            bufferedWriter.write(" secs" + Constants.LINE_SEPARATOR);
            // Last event
            String lastEventDatestamp = JdkUtil.getDateStamp(jvmRun.getLastEvent().getLogEntry());
            if (lastEventDatestamp != null) {
                bufferedWriter.write("Last Datestamp: ");
                bufferedWriter.write(lastEventDatestamp);
                bufferedWriter.write(Constants.LINE_SEPARATOR);
            }
            bufferedWriter.write("Last Timestamp: ");
            BigDecimal lastEventTimestamp = JdkMath.convertMillisToSecs(jvmRun.getLastEvent().getTimestamp());
            bufferedWriter.write(lastEventTimestamp.toString());
            bufferedWriter.write(" secs" + Constants.LINE_SEPARATOR);
        }

        bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR);

        // Analysis
        List<Analysis> analysis = jvmRun.getAnalysis();
        if (!analysis.isEmpty()) {

            // Determine analysis levels
            List<Analysis> error = new ArrayList<Analysis>();
            List<Analysis> warn = new ArrayList<Analysis>();
            List<Analysis> info = new ArrayList<Analysis>();

            Iterator<Analysis> iterator = analysis.iterator();
            while (iterator.hasNext()) {
                Analysis a = iterator.next();
                String level = a.getKey().split("\\.")[0];
                if (level.equals("error")) {
                    error.add(a);
                } else if (level.equals("warn")) {
                    warn.add(a);
                } else if (level.equals("info")) {
                    info.add(a);
                } else {
                    throw new IllegalArgumentException("Unknown analysis level: " + level);
                }
            }

            bufferedWriter.write("ANALYSIS:" + Constants.LINE_SEPARATOR);

            iterator = error.iterator();
            boolean printHeader = true;
            // ERROR
            while (iterator.hasNext()) {
                if (printHeader) {
                    bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);
                    bufferedWriter.write("error" + Constants.LINE_SEPARATOR);
                    bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);
                }
                printHeader = false;
                Analysis a = iterator.next();
                bufferedWriter.write("*");
                bufferedWriter.write(a.getValue());
                bufferedWriter.write(Constants.LINE_SEPARATOR);
            }
            // WARN
            iterator = warn.iterator();
            printHeader = true;
            while (iterator.hasNext()) {
                if (printHeader) {
                    bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);
                    bufferedWriter.write("warn" + Constants.LINE_SEPARATOR);
                    bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);
                }
                printHeader = false;
                Analysis a = iterator.next();
                bufferedWriter.write("*");
                bufferedWriter.write(a.getValue());
                bufferedWriter.write(Constants.LINE_SEPARATOR);
            }
            // INFO
            iterator = info.iterator();
            printHeader = true;
            while (iterator.hasNext()) {
                if (printHeader) {
                    bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);
                    bufferedWriter.write("info" + Constants.LINE_SEPARATOR);
                    bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);
                }
                printHeader = false;
                Analysis a = iterator.next();
                bufferedWriter.write("*");
                bufferedWriter.write(a.getValue());
                bufferedWriter.write(Constants.LINE_SEPARATOR);
            }
            bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR);
        }

        // Unidentified log lines
        List<String> unidentifiedLogLines = jvmRun.getUnidentifiedLogLines();
        if (!unidentifiedLogLines.isEmpty()) {
            bufferedWriter.write(
                    unidentifiedLogLines.size() + " UNIDENTIFIED LOG LINE(S):" + Constants.LINE_SEPARATOR);
            bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR);

            Iterator<String> iterator = unidentifiedLogLines.iterator();
            while (iterator.hasNext()) {
                String unidentifiedLogLine = iterator.next();
                bufferedWriter.write(unidentifiedLogLine);
                bufferedWriter.write(Constants.LINE_SEPARATOR);
            }
            bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR);
        }
    } catch (

    FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // Close streams
        if (bufferedWriter != null) {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fileWriter != null) {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.dbflute.solr.cbean.SolrQueryBuilder.java

/**
 * //from   www  .  jav  a2s  .  co  m
 * @param solrFieldName
 * @param queryList
 * @param operator
 * @return 
 */
public static String queryBuilderForSearchBigDecimalList(String solrFieldName, Collection<BigDecimal> queryList,
        SolrQueryLogicalOperator operator) {
    List<String> queryStrList = new ArrayList<String>();
    if (isNotEmptyStrict(queryList)) {
        for (BigDecimal num : queryList) {
            queryStrList.add(num.toString());
        }
    }
    return queryBuilderForSearchWordList(solrFieldName, queryStrList, operator);
}