Example usage for java.text DecimalFormat setDecimalFormatSymbols

List of usage examples for java.text DecimalFormat setDecimalFormatSymbols

Introduction

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

Prototype

public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols) 

Source Link

Document

Sets the decimal format symbols, which is generally not changed by the programmer or user.

Usage

From source file:chibi.gemmaanalysis.CorrelationAnalysisCLI.java

@Override
protected Exception doWork(String[] args) {
    Exception exc = processCommandLine(args);
    if (exc != null) {
        return exc;
    }//www .j  a  v  a2  s  . co  m

    Collection<Gene> queryGenes, targetGenes;
    try {
        queryGenes = getQueryGenes();
        targetGenes = getTargetGenes();
    } catch (IOException e) {
        return e;
    }

    // calculate matrices
    CoexpressionMatrices matrices = coexpressionAnalysisService.calculateCoexpressionMatrices(
            expressionExperiments, queryGenes, targetGenes, filterConfig, CorrelationMethod.SPEARMAN);
    DenseDouble3dMatrix<Gene, Gene, BioAssaySet> correlationMatrix = matrices.getCorrelationMatrix();
    // DenseDoubleMatrix3DNamed sampleSizeMatrix = matrices
    // .getSampleSizeMatrix();

    // DoubleMatrixNamed maxCorrelationMatrix = coexpressionAnalysisService
    // .getMaxCorrelationMatrix(correlationMatrix, kMax);
    // DoubleMatrixNamed pValMatrix = coexpressionAnalysisService
    // .calculateMaxCorrelationPValueMatrix(maxCorrelationMatrix,
    // kMax, ees);
    // DoubleMatrixNamed effectSizeMatrix = coexpressionAnalysisService
    // .calculateEffectSizeMatrix(correlationMatrix, sampleSizeMatrix);

    // get row/col name maps
    Map<Gene, String> geneNameMap = matrices.getGeneNameMap();
    Map<ExpressionExperiment, String> eeNameMap = matrices.getEeNameMap();

    DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    formatter.applyPattern("0.0000");
    DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
    symbols.setNaN("NaN");
    formatter.setDecimalFormatSymbols(symbols);

    try {
        MatrixWriter<Gene, Gene> matrixOut;
        matrixOut = new MatrixWriter<Gene, Gene>(outFilePrefix + ".corr.txt", formatter);
        matrixOut.setSliceNameMap(eeNameMap);
        matrixOut.setRowNameMap(geneNameMap);
        matrixOut.setColNameMap(geneNameMap);
        matrixOut.writeMatrix(correlationMatrix, false);

        try (PrintWriter out = new PrintWriter(new FileWriter(outFilePrefix + ".corr.row_names.txt"));) {
            List<Gene> rows = correlationMatrix.getRowNames();
            for (Gene row : rows) {
                out.println(row);
            }
        }

        try (PrintWriter out = new PrintWriter(new FileWriter(outFilePrefix + ".corr.col_names.txt"));) {
            Collection<BioAssaySet> cols = correlationMatrix.getSliceNames();
            for (BioAssaySet bas : cols) {
                ExpressionExperiment ee = (ExpressionExperiment) bas;
                out.println(ee.getShortName());
            }
        }
    } catch (IOException e) {
        return e;
    }
    // out = new MatrixWriter(outFilePrefix + ".max_corr.txt", formatter,
    // geneNameMap, geneNameMap);
    // out.writeMatrix(maxCorrelationMatrix, true);
    // out.close();
    //
    // out = new MatrixWriter(outFilePrefix + ".max_corr.pVal.txt",
    // formatter, geneNameMap, geneNameMap);
    // out.writeMatrix(pValMatrix, true);
    // out.close();
    //
    // out = new MatrixWriter(outFilePrefix + ".effect_size.txt",
    // formatter, geneNameMap, geneNameMap);
    // out.writeMatrix(effectSizeMatrix, true);
    // out.close();

    return null;
}

From source file:org.apache.cocoon.template.instruction.FormatNumber.java

private void setCurrency(NumberFormat formatter, String currencyCode, String currencySymbol) throws Exception {
    String code = null;/*from  w  ww  .ja  v a2  s .  c  om*/
    String symbol = null;

    if (currencyCode == null) {
        if (currencySymbol == null) {
            return;
        }
        symbol = currencySymbol;
    } else if (currencySymbol != null) {
        if (currencyClass != null) {
            code = currencyCode;
        } else {
            symbol = currencySymbol;
        }
    } else if (currencyClass != null) {
        code = currencyCode;
    } else {
        symbol = currencyCode;
    }
    if (code != null) {
        Object[] methodArgs = new Object[1];

        /*
         * java.util.Currency.getInstance()
         */
        Method m = currencyClass.getMethod("getInstance", new Class[] { String.class });

        methodArgs[0] = code;
        Object currency = m.invoke(null, methodArgs);

        /*
         * java.text.NumberFormat.setCurrency()
         */
        Class[] paramTypes = new Class[1];
        paramTypes[0] = currencyClass;
        Class numberFormatClass = Class.forName("java.text.NumberFormat");
        m = numberFormatClass.getMethod("setCurrency", paramTypes);
        methodArgs[0] = currency;
        m.invoke(formatter, methodArgs);
    } else {
        /*
         * Let potential ClassCastException propagate up (will almost never
         * happen)
         */
        DecimalFormat df = (DecimalFormat) formatter;
        DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
        dfs.setCurrencySymbol(symbol);
        df.setDecimalFormatSymbols(dfs);
    }
}

From source file:com.epam.dlab.core.parser.CommonFormat.java

/**
 * Create and return decimal formatter./*from ww w. ja  v  a 2s.c om*/
 *
 * @param decimalSeparator  the character used for decimal sign.
 * @param groupingSeparator the character used for thousands separator.
 * @return Formatter for decimal digits.
 */
private DecimalFormat getDecimalFormat(char decimalSeparator, char groupingSeparator) {
    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator(decimalSeparator);
    symbols.setGroupingSeparator(groupingSeparator);
    df.setDecimalFormatSymbols(symbols);
    return df;
}

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

/**
 * reserve used ratio of process CPU and total CPU, meanwhile collect
 * network traffic./*  w  w  w  .j  a  v a  2 s. c o m*/
 * 
 * @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:ub.botiga.ServletDispatcher.java

private void showCistell(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    User u = (User) session.getAttribute("user");
    if (u == null) {
        response.sendRedirect("/Botiga/");
        return;//  www . ja v a  2s .  c o  m
    }

    HashMap<String, Product> cistell = getCistell(request);
    HashMap<String, Product> historial = u.getProducts();
    for (Product p : historial.values()) {
        cistell.remove(p.getName());
    }
    session.setAttribute("cistell", cistell);
    if (u.getCredits() - getPreuCistell(request) < 0) {
        request.setAttribute("creditsuficient", false);
    } else {
        request.setAttribute("creditsuficient", true);
    }

    request.setAttribute("cistell", cistell.values());
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(2);
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');

    df.setDecimalFormatSymbols(dfs);
    request.setAttribute("preucistell", df.format(getPreuCistell(request)));
    showPage(request, response, "cistell.jsp");
}

From source file:org.totschnig.myexpenses.util.Utils.java

/**
 * @param currency//ww  w.j av a 2s.c o m
 * @param separator
 * @return a Decimalformat with the number of fraction digits appropriate for
 *         currency, and with the given separator, but without the currency
 *         symbol appropriate for CSV and QIF export
 */
public static DecimalFormat getDecimalFormat(Currency currency, char separator) {
    DecimalFormat nf = new DecimalFormat();
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator(separator);
    nf.setDecimalFormatSymbols(symbols);
    int fractionDigits = currency.getDefaultFractionDigits();
    if (fractionDigits != -1) {
        nf.setMinimumFractionDigits(fractionDigits);
        nf.setMaximumFractionDigits(fractionDigits);
    } else {
        nf.setMaximumFractionDigits(Money.DEFAULTFRACTIONDIGITS);
    }
    nf.setGroupingUsed(false);
    return nf;
}

From source file:org.openehr.rm.datatypes.quantity.DvQuantity.java

/**
 * string form displayable for humans/*from  w w w .  ja  va2  s .co m*/
 *
 * @return string presentation
 */
public String toString() {
    DecimalFormat format = new DecimalFormat();
    format.setMinimumFractionDigits(precision);
    format.setMaximumFractionDigits(precision);
    DecimalFormatSymbols dfs = format.getDecimalFormatSymbols();
    dfs.setDecimalSeparator(DECIMAL_SEPARATOR);
    format.setDecimalFormatSymbols(dfs);
    format.setGroupingUsed(false);
    String tmp = format.format(magnitude) + (StringUtils.isEmpty(getUnits()) ? "" : "," + getUnits());
    return tmp;
}

From source file:com.github.fritaly.dualcommander.DirectoryBrowser.java

private void updateSummary(Iterable<File> iterable) {
    Validate.notNull(iterable, "The give iterable is null");

    int files = 0, folders = 0;
    long totalSize = 0;

    for (File file : iterable) {
        if (file.isFile()) {
            files++;/* w  w  w  . j a va  2 s.c o  m*/
            totalSize += file.length();
        } else {
            folders++;
        }
    }

    final DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
    symbols.setGroupingSeparator(' ');

    final DecimalFormat decimalFormat = new DecimalFormat();
    decimalFormat.setDecimalFormatSymbols(symbols);

    // Set the summary
    if (files > 0) {
        if (folders > 0) {
            summary.setText(String.format("%d folder(s) and %d file(s) [%s Kb]", folders, files,
                    decimalFormat.format(totalSize / 1024)));
        } else {
            summary.setText(String.format("%d file(s) [%s Kb]", files, decimalFormat.format(totalSize / 1024)));
        }
    } else {
        if (folders > 0) {
            summary.setText(String.format("%d folder(s)", folders));
        } else {
            summary.setText(" ");
        }
    }
}

From source file:py.una.pol.karaku.util.FormatProvider.java

private NumberFormat getNumberFormat(String format) {

    DecimalFormat df = new DecimalFormat(format);
    df.setDecimalFormatSymbols(this.getDFS());
    return df;/*  w  w  w.  j a v  a 2  s .  c o m*/
}

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

public void run() {

    initParameters();/*w  w w  . ja  v a  2 s  . c o m*/

    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);
}