Example usage for java.text DecimalFormat setMaximumFractionDigits

List of usage examples for java.text DecimalFormat setMaximumFractionDigits

Introduction

In this page you can find the example usage for java.text DecimalFormat setMaximumFractionDigits.

Prototype

@Override
public void setMaximumFractionDigits(int newValue) 

Source Link

Document

Sets the maximum number of digits allowed in the fraction portion of a number.

Usage

From source file:com.blackbear.flatworm.converters.CoreConverters.java

public String convertDecimal(Object obj, Map<String, ConversionOption> options) {
    Double d = (Double) obj;
    if (d == null) {
        return null;
    }/*w w w.ja  v  a 2 s  .co  m*/

    int decimalPlaces = 0;
    ConversionOption conv = (ConversionOption) options.get("decimal-places");

    String decimalPlacesOption = null;
    if (null != conv)
        decimalPlacesOption = conv.getValue();

    boolean decimalImplied = "true".equals(Util.getValue(options, "decimal-implied"));

    if (decimalPlacesOption != null)
        decimalPlaces = Integer.parseInt(decimalPlacesOption);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalSeparatorAlwaysShown(!decimalImplied);
    format.setGroupingUsed(false);
    if (decimalImplied) {
        format.setMaximumFractionDigits(0);
        d = new Double(d.doubleValue() * Math.pow(10D, decimalPlaces));
    } else {
        format.setMinimumFractionDigits(decimalPlaces);
        format.setMaximumFractionDigits(decimalPlaces);
    }
    return format.format(d);
}

From source file:org.openbravo.advpaymentmngt.utility.FIN_Utility.java

/**
 * Convert a multi currency amount to a string for display in the UI. If amount has been converted
 * to a different currency, then output that converted amount and currency as well
 * /*from  w w  w . j  a  v  a  2  s.c  o m*/
 * @param amt
 *          Amount of payment
 * @param currency
 *          Currency payment was made in
 * @param convertedAmt
 *          Amount of payment in converted currency
 * @param convertedCurrency
 *          Currency payment was converted to/from
 * @return String version of amount formatted for display to user
 */
public static String multiCurrencyAmountToDisplay(BigDecimal amt, Currency currency, BigDecimal convertedAmt,
        Currency convertedCurrency) {
    StringBuffer out = new StringBuffer();
    final UIDefinitionController.FormatDefinition formatDef = UIDefinitionController.getInstance()
            .getFormatDefinition("euro", "Edition");

    String formatWithDot = formatDef.getFormat();
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    try {
        dfs.setDecimalSeparator(formatDef.getDecimalSymbol().charAt(0));
        dfs.setGroupingSeparator(formatDef.getGroupingSymbol().charAt(0));
        // Use . as decimal separator
        final String DOT = ".";
        if (!DOT.equals(formatDef.getDecimalSymbol())) {
            formatWithDot = formatWithDot.replace(formatDef.getGroupingSymbol(), "@");
            formatWithDot = formatWithDot.replace(formatDef.getDecimalSymbol(), ".");
            formatWithDot = formatWithDot.replace("@", ",");
        }
    } catch (Exception e) {
        // If any error use euroEdition default format
        formatWithDot = "#0.00";
    }
    DecimalFormat amountFormatter = new DecimalFormat(formatWithDot, dfs);
    amountFormatter.setMaximumFractionDigits(currency.getStandardPrecision().intValue());

    out.append(amountFormatter.format(amt));
    if (convertedCurrency != null && !currency.equals(convertedCurrency)
            && amt.compareTo(BigDecimal.ZERO) != 0) {
        amountFormatter.setMaximumFractionDigits(convertedCurrency.getStandardPrecision().intValue());
        out.append(" (").append(amountFormatter.format(convertedAmt)).append(" ")
                .append(convertedCurrency.getISOCode()).append(")");
    }

    return out.toString();
}

From source file:com.netease.qa.emmagee.utils.CpuInfo.java

/**
 * reserve used ratio of process CPU and total CPU, meanwhile collect
 * network traffic./*from   w w  w .j  a  v a2 s. c om*/
 * 
 * @return network traffic ,used ratio of process CPU and total CPU in
 *         certain interval
 */
public ArrayList<String> getCpuRatioInfo(String totalBatt, String currentBatt, String temperature,
        String voltage, String fps, boolean isRoot) {

    String heapData = "";
    DecimalFormat fomart = new DecimalFormat();
    fomart.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    fomart.setGroupingUsed(false);
    fomart.setMaximumFractionDigits(2);
    fomart.setMinimumFractionDigits(2);

    cpuUsedRatio.clear();
    idleCpu.clear();
    totalCpu.clear();
    totalCpuRatio.clear();
    readCpuStat();

    try {
        String mDateTime2;
        Calendar cal = Calendar.getInstance();
        if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"))) {
            mDateTime2 = formatterFile.format(cal.getTime().getTime() + 8 * 60 * 60 * 1000);
            totalBatt = Constants.NA;
            currentBatt = Constants.NA;
            temperature = Constants.NA;
            voltage = Constants.NA;
        } else
            mDateTime2 = formatterFile.format(cal.getTime().getTime());
        if (isInitialStatics) {
            preTraffic = trafficInfo.getTrafficInfo();
            isInitialStatics = false;
        } else {
            lastestTraffic = trafficInfo.getTrafficInfo();
            if (preTraffic == -1)
                traffic = -1;
            else {
                if (lastestTraffic > preTraffic) {
                    traffic += (lastestTraffic - preTraffic + 1023) / 1024;
                }
            }
            preTraffic = lastestTraffic;
            Log.d(LOG_TAG, "lastestTraffic===" + lastestTraffic);
            Log.d(LOG_TAG, "preTraffic===" + preTraffic);
            StringBuffer totalCpuBuffer = new StringBuffer();
            if (null != totalCpu2 && totalCpu2.size() > 0) {
                processCpuRatio = fomart.format(100 * ((double) (processCpu - processCpu2)
                        / ((double) (totalCpu.get(0) - totalCpu2.get(0)))));
                for (int i = 0; i < (totalCpu.size() > totalCpu2.size() ? totalCpu2.size()
                        : totalCpu.size()); i++) {
                    String cpuRatio = "0.00";
                    if (totalCpu.get(i) - totalCpu2.get(i) > 0) {
                        cpuRatio = fomart.format(100 * ((double) ((totalCpu.get(i) - idleCpu.get(i))
                                - (totalCpu2.get(i) - idleCpu2.get(i)))
                                / (double) (totalCpu.get(i) - totalCpu2.get(i))));
                    }
                    totalCpuRatio.add(cpuRatio);
                    totalCpuBuffer.append(cpuRatio + Constants.COMMA);
                }
            } else {
                processCpuRatio = "0";
                totalCpuRatio.add("0");
                totalCpuBuffer.append("0,");
                totalCpu2 = (ArrayList<Long>) totalCpu.clone();
                processCpu2 = processCpu;
                idleCpu2 = (ArrayList<Long>) idleCpu.clone();
            }
            // cpucsv
            for (int i = 0; i < getCpuNum() - totalCpuRatio.size() + 1; i++) {
                totalCpuBuffer.append("0.00,");
            }
            long pidMemory = mi.getPidMemorySize(pid, context);
            String pMemory = fomart.format((double) pidMemory / 1024);
            long freeMemory = mi.getFreeMemorySize(context);
            String fMemory = fomart.format((double) freeMemory / 1024);
            String percent = context.getString(R.string.stat_error);
            if (totalMemorySize != 0) {
                percent = fomart.format(((double) pidMemory / (double) totalMemorySize) * 100);
            }

            if (isPositive(processCpuRatio) && isPositive(totalCpuRatio.get(0))) {
                String trafValue;
                // whether certain device supports traffic statics or not
                if (traffic == -1) {
                    trafValue = Constants.NA;
                } else {
                    trafValue = String.valueOf(traffic);
                }
                if (isRoot) {
                    String[][] heapArray = MemoryInfo.getHeapSize(pid, context);
                    heapData = heapArray[0][1] + "/" + heapArray[0][0] + Constants.COMMA + heapArray[1][1] + "/"
                            + heapArray[1][0] + Constants.COMMA;
                }
                EmmageeService.bw.write(mDateTime2 + Constants.COMMA + ProcessInfo.getTopActivity(context)
                        + Constants.COMMA + heapData + pMemory + Constants.COMMA + percent + Constants.COMMA
                        + fMemory + Constants.COMMA + processCpuRatio + Constants.COMMA
                        + totalCpuBuffer.toString() + trafValue + Constants.COMMA + totalBatt + Constants.COMMA
                        + currentBatt + Constants.COMMA + temperature + Constants.COMMA + voltage
                        + Constants.COMMA + fps + Constants.LINE_END);

                JSONObject jsonobj = new JSONObject();
                JSONArray jsonarr = new JSONArray();
                jsonarr.put(System.currentTimeMillis());
                jsonarr.put(pMemory);
                jsonarr.put(percent);
                jsonarr.put(fMemory);
                jsonarr.put(processCpuRatio);
                jsonarr.put(totalCpuBuffer.toString().split(",")[0]);
                jsonarr.put(trafValue);
                jsonarr.put(totalBatt);
                jsonarr.put(currentBatt);
                jsonarr.put(temperature);
                jsonarr.put(voltage);
                jsonarr.put(fps);
                jsonobj.put("testSuitId", HttpUtils.testSuitId);
                jsonobj.put("data", jsonarr);

                HttpUtils.postAppPerfData(jsonobj.toString());

                totalCpu2 = (ArrayList<Long>) totalCpu.clone();
                processCpu2 = processCpu;
                idleCpu2 = (ArrayList<Long>) idleCpu.clone();
                cpuUsedRatio.add(processCpuRatio);
                cpuUsedRatio.add(totalCpuRatio.get(0));
                cpuUsedRatio.add(String.valueOf(traffic));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return cpuUsedRatio;
}

From source file:lirmm.inria.fr.math.BigSparseRealMatrix.java

@Override
public String toString() {
    DecimalFormat df;
    df = new DecimalFormat();
    df.setMaximumFractionDigits(2); //arrondi  2 chiffres apres la virgules
    df.setMinimumFractionDigits(2);//from  ww w  . j a  va 2s.c  om
    df.setDecimalSeparatorAlwaysShown(true);
    String out = "";
    for (int i = 0; i < getRowDimension(); i++) {
        String o = "";
        for (int j = 0; j < getColumnDimension(); j++) {
            out += df.format(getEntry(i, j)).replaceAll(",", ".") + " ";
            o += df.format(getEntry(i, j)).replaceAll(",", ".") + " ";
        }
        out += "\n";
    }
    return out;
}

From source file:org.sdr.webrec.core.WebRec.java

public void run() {

    initParameters();/* w w w.ja va 2s .  com*/

    String transactionName = "";
    HttpResponse response = null;

    DecimalFormat formatter = new DecimalFormat("#####0.00");
    DecimalFormatSymbols dfs = formatter.getDecimalFormatSymbols();
    formatter.setMinimumFractionDigits(3);
    formatter.setMaximumFractionDigits(3);

    // make sure delimeter is a '.' instead of locale default ','
    dfs.setDecimalSeparator('.');
    formatter.setDecimalFormatSymbols(dfs);

    do {
        t1 = System.currentTimeMillis();
        URL siteURL = null;
        try {

            for (int i = 0; i < url.length; i++) {

                LOGGER.debug("url:" + ((Transaction) url[i]).getUrl());

                Transaction transaction = (Transaction) url[i];
                siteURL = new URL(transaction.getUrl());
                transactionName = transaction.getName();

                //if transaction requires server authentication
                if (transaction.isAutenticate())
                    httpclient.getCredentialsProvider().setCredentials(
                            new AuthScope(siteURL.getHost(), siteURL.getPort()),
                            new UsernamePasswordCredentials(transaction.getWorkload().getUsername(),
                                    transaction.getWorkload().getPassword()));

                // Get HTTP GET method
                httpget = new HttpGet(((Transaction) url[i]).getUrl());

                double startTime = System.nanoTime();

                double endTime = 0.00d;

                response = null;

                // Execute HTTP GET
                try {
                    response = httpclient.execute(httpget);
                    endTime = System.nanoTime();

                } catch (Exception e) {
                    httpget.abort();
                    LOGGER.error("ERROR in receiving response:" + e.getLocalizedMessage());
                    e.printStackTrace();
                }

                double timeLapse = 0;

                if (response != null) {
                    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {

                        timeLapse = endTime - startTime;

                        LOGGER.debug("starttime:" + (new Double(startTime)).toString());
                        LOGGER.debug("timeLapse:" + endTime);
                        LOGGER.debug("timeLapse:" + timeLapse);

                        //move nanos to millis
                        timeLapse = timeLapse / 1000000L;
                        LOGGER.debug("response time:" + formatter.format(timeLapse) + "ms.");
                        out.write(System.currentTimeMillis() / 1000 + ":");
                        out.write(
                                threadName + '.' + transactionName + ":" + formatter.format(timeLapse) + "\n");

                        //content must be consumed just because 
                        //otherwice apache httpconnectionmanager does not release connection back to pool
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            EntityUtils.toByteArray(entity);
                        }

                    } else {
                        LOGGER.error("Status code of transaction:" + transactionName + " was not "
                                + HttpURLConnection.HTTP_OK + " but "
                                + response.getStatusLine().getStatusCode());
                    }

                }
                int sleepTime = delay;
                try {
                    LOGGER.debug("Sleeping " + delay / 1000 + "s...");
                    sleep(sleepTime);
                } catch (InterruptedException ie) {
                    LOGGER.error("ERROR:" + ie);
                    ie.printStackTrace();
                }
            }
        } catch (Exception e) {
            LOGGER.error("Error in thread " + threadName + " with url:" + siteURL + " " + e.getMessage());
            e.printStackTrace();
        }
        try {
            out.flush();
            t2 = System.currentTimeMillis();
            tTask = t2 - t1;

            LOGGER.debug("Total time consumed:" + tTask / 1000 + "s.");

            if (tTask <= interval) {
                //when task takes less than preset time
                LOGGER.debug("Sleeping interval:" + (interval - tTask) / 1000 + "s.");
                sleep(interval - tTask);
            }

            cm.closeExpiredConnections();
        } catch (InterruptedException ie) {
            LOGGER.error("Error:" + ie);
            ie.printStackTrace();
        } catch (Exception e) {
            LOGGER.error("Error:" + e);
            e.printStackTrace();
        }
    } while (true);
}

From source file:com.magestore.app.pos.service.config.POSConfigService.java

private DecimalFormat floatFormat(ConfigPriceFormat priceFormat) {
    // khi to float format
    String pattern = "###,###.#";
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    symbols.setDecimalSeparator(priceFormat.getDecimalSymbol().charAt(0));
    symbols.setGroupingSeparator(priceFormat.getGroupSymbol().charAt(0));
    DecimalFormat format = new DecimalFormat(pattern, symbols);
    format.setGroupingSize(priceFormat.getGroupLength());
    format.setMaximumFractionDigits(priceFormat.getPrecision());
    format.setMinimumFractionDigits(priceFormat.getRequirePrecision());
    return format;
}

From source file:com.magestore.app.pos.service.config.POSConfigService.java

private DecimalFormat quantityFormat(ConfigQuantityFormat quantityFormat) {
    // khi to interger format
    // khi to float format
    String pattern = "###,###.#";
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    symbols.setDecimalSeparator(quantityFormat.getDecimalSymbol().charAt(0));
    symbols.setGroupingSeparator(quantityFormat.getGroupSymbol().charAt(0));
    DecimalFormat format = new DecimalFormat(pattern, symbols);
    format.setGroupingSize(quantityFormat.getGroupLength());
    format.setMaximumFractionDigits(quantityFormat.getPrecision());
    format.setMinimumFractionDigits(0);//from w w  w  . j av a2s  . c  om
    return format;
}

From source file:com.magestore.app.pos.service.config.POSConfigService.java

private DecimalFormat currencyFormat(ConfigPriceFormat priceFormat) {
    // khi to currency format
    String pattern = "###,###.#";
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    symbols.setDecimalSeparator('.');
    symbols.setGroupingSeparator('.');
    DecimalFormat currencyFormat = new DecimalFormat(pattern, symbols);
    currencyFormat.setGroupingSize(priceFormat.getGroupLength());
    currencyFormat.setMaximumFractionDigits(priceFormat.getPrecision());
    currencyFormat.setMinimumFractionDigits(priceFormat.getRequirePrecision());
    return currencyFormat;
}

From source file:com.magestore.app.pos.service.config.POSConfigService.java

private DecimalFormat currencyNosymbolFormat(ConfigPriceFormat priceFormat) {
    // khi to currency format
    String pattern = "###,###.#";
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    symbols.setDecimalSeparator(priceFormat.getDecimalSymbol().charAt(0));
    symbols.setGroupingSeparator(priceFormat.getGroupSymbol().charAt(0));
    DecimalFormat currencyFormat = new DecimalFormat(pattern, symbols);
    currencyFormat.setGroupingSize(priceFormat.getGroupLength());
    currencyFormat.setMaximumFractionDigits(priceFormat.getPrecision());
    currencyFormat.setMinimumFractionDigits(priceFormat.getRequirePrecision());
    return currencyFormat;
}

From source file:io.bitsquare.gui.util.BSFormatter.java

public String formatToPercent(double value) {
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    decimalFormat.setMinimumFractionDigits(2);
    decimalFormat.setMaximumFractionDigits(2);
    return decimalFormat.format(MathUtils.roundDouble(value * 100.0, 2)).replace(",", ".");
}