Example usage for java.text NumberFormat setMaximumFractionDigits

List of usage examples for java.text NumberFormat setMaximumFractionDigits

Introduction

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

Prototype

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.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * Starts uploading data./*  w w w .j a  v a 2s  .c o m*/
 */
private void startUploading() {
    if (uploadThread != null) {
        writeToLog("Upload thread active");
        return;
    }

    uploadThread = new Thread(new Runnable() {
        @Override
        public void run() {
            uploadThreadRunning = true;

            while (uploadThreadRunning) {
                //get API key
                retrieveApiKey();

                //get a list of non uploaded measurements
                MeasurementsDBIterator dbIterator = mDatabase.getNonUploadedMeasurements();
                boolean success = true;
                String errorMsg = "";
                int max = 0;

                int count = 0;

                // stop uploading if the upload is working only when the wifi is active 
                if (wifiOnly && !NetUtils.isWifiConnected(getApplicationContext())) {
                    writeToLog("WiFi only and WiFi is not connected.");
                    try {
                        Thread.sleep(newDataCheckInterval);
                    } catch (Exception e) {
                    }

                    continue;
                }

                try {
                    writeToLog("Checking if there are records for upload...");
                    if (dbIterator.getCount() > 0) {

                        httpclient = new DefaultHttpClient();
                        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                                HttpVersion.HTTP_1_0);

                        writeToLog("MeasurementsUploaderService startUploading() - openCellUrl=" + openCellUrl);

                        httppost = new HttpPost(openCellUrl);

                        max = dbIterator.getCount();
                        count = 0;

                        NumberFormat latLonFormat = NumberFormat.getNumberInstance(Locale.US);
                        latLonFormat.setMaximumFractionDigits(10);

                        while (dbIterator.hasNext() && uploadThreadRunning) {
                            //upload measurements as a batch file
                            count = uploadMeasurementsBatch(dbIterator, latLonFormat, count, max);
                            Intent progress = new Intent(OpenCellIDUploadService.BROADCAST_PROGRESS_ACTION);
                            progress.putExtra(OpenCellIDUploadService.XTRA_MAXPROGRESS, max);
                            progress.putExtra(OpenCellIDUploadService.XTRA_PROGRESS, count);
                            sendBroadcast(progress);
                        }

                        // set all measurements as uploaded
                        if (uploadThreadRunning) {
                            mDatabase.setAllMeasurementsUploaded();
                        }

                        // start uploading networks data
                        if (uploadThreadRunning) {
                            uploadNetworks();
                        }

                        writeToLog("Uploaded " + count + " of " + max + " records.");
                        httpclient.getConnectionManager().shutdown();
                        success = true;
                    } else {
                        writeToLog("No records for upload right now.");
                    }

                } catch (Exception e) {
                    writeExceptionToLog(e);
                    success = false;
                    errorMsg = e.getMessage();
                } finally {
                    dbIterator.close();
                }

                Intent progress = new Intent(OpenCellIDUploadService.BROADCAST_PROGRESS_ACTION);
                progress.putExtra(OpenCellIDUploadService.XTRA_MAXPROGRESS, max);
                progress.putExtra(OpenCellIDUploadService.XTRA_PROGRESS, count);
                progress.putExtra(OpenCellIDUploadService.XTRA_DONE, true);
                progress.putExtra(OpenCellIDUploadService.XTRA_SUCCESS, success);

                if (!success) {
                    progress.putExtra(OpenCellIDUploadService.XTRA_FAILURE_MSG, errorMsg);
                }
                sendBroadcast(progress);

                try {
                    Thread.sleep(newDataCheckInterval);
                } catch (Exception e) {
                }
            }
        }
    });
    uploadThread.start();
}

From source file:ubic.gemma.datastructure.matrix.ExpressionDataDoubleMatrix.java

@Override
public String toString() {
    int columns = this.columns();
    int rows = this.rows();

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(4);

    StringBuffer buf = new StringBuffer();
    if (rows <= MAX_ROWS_TO_STRING) {
        buf.append(rows + " x " + columns + " matrix of double values\n");
    } else {/*from   w  w w .j  a v  a  2 s. co m*/
        buf.append(rows + " x " + columns + " matrix of double values, showing up to " + MAX_ROWS_TO_STRING
                + " rows\n");
    }
    int stop = 0;
    buf.append("Probe");
    for (int i = 0; i < columns; i++) {
        buf.append("\t" + this.getBioMaterialForColumn(i).getName() + ":");
        for (BioAssay ba : this.getBioAssaysForColumn(i)) {
            buf.append(ba.getName() + ",");
        }
    }
    buf.append("\n");

    for (int j = 0; j < rows; j++) {

        buf.append(this.rowDesignElementMapByInteger.get(j).getName());
        for (int i = 0; i < columns; i++) {
            Double val = this.get(j, i);
            if (Double.isNaN(val)) {
                buf.append("\t" + val);
            } else {
                buf.append("\t" + nf.format(this.get(j, i)));
            }
        }

        buf.append("\n");

        if (stop++ > MAX_ROWS_TO_STRING) {
            buf.append("\n(Stopping after " + MAX_ROWS_TO_STRING + " rows) ...\n");
            break;
        }
    }
    return buf.toString();
}

From source file:ubic.gemma.core.analysis.expression.coexpression.links.LinkAnalysisServiceImpl.java

/**
 * Write links as text./*from ww w.jav  a2 s  . c  o m*/
 */
private void writeLinks(final LinkAnalysis la, FilterConfig filterConfig, Writer wr) throws IOException {
    Map<CompositeSequence, Set<Gene>> probeToGeneMap = la.getProbeToGeneMap();
    ObjectArrayList links = la.getKeep();
    double subsetSize = la.getConfig().getSubsetSize();
    List<String> buf = new ArrayList<>();
    if (la.getConfig().isSubset() && links.size() > subsetSize) {
        la.getConfig().setSubsetUsed(true);
    }
    wr.write(la.getConfig().toString());
    wr.write(filterConfig.toString());
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(4);

    Integer probeDegreeThreshold = la.getConfig().getProbeDegreeThreshold();

    int i = 0;
    int keptLinksCount = 0;
    Random generator = new Random();
    double rand;
    double fraction = subsetSize / links.size();
    int skippedDueToDegree = 0;
    for (int n = links.size(); i < n; i++) {

        Object val = links.getQuick(i);
        if (val == null)
            continue;
        Link m = (Link) val;
        Double w = m.getWeight();

        int x = m.getx();
        int y = m.gety();

        if (probeDegreeThreshold > 0 && (la.getProbeDegree(x) > probeDegreeThreshold
                || la.getProbeDegree(y) > probeDegreeThreshold)) {
            skippedDueToDegree++;
            continue;
        }

        CompositeSequence p1 = la.getProbe(x);
        CompositeSequence p2 = la.getProbe(y);

        Set<Gene> g1 = probeToGeneMap.get(p1);
        Set<Gene> g2 = probeToGeneMap.get(p2);

        List<String> genes1 = new ArrayList<>();
        for (Gene cluster : g1) {
            String t = cluster.getOfficialSymbol();
            genes1.add(t);
        }

        List<String> genes2 = new ArrayList<>();
        for (Gene cluster : g2) {
            String t = cluster.getOfficialSymbol();
            genes2.add(t);
        }

        if (genes2.size() == 0 || genes1.size() == 0) {
            continue;
        }

        String gene1String = StringUtils.join(genes1.iterator(), "|");
        String gene2String = StringUtils.join(genes2.iterator(), "|");

        if (gene1String.equals(gene2String)) {
            continue;
        }

        if (++keptLinksCount % 50000 == 0) {
            LinkAnalysisServiceImpl.log.info(keptLinksCount + " links retained");
        }

        if (la.getConfig().isSubsetUsed()) {
            rand = generator.nextDouble();
            if (rand > fraction)
                continue;
        }

        buf.add(p1.getId() + "\t" + p2.getId() + "\t" + gene1String + "\t" + gene2String + "\t" + nf.format(w)
                + "\n");// save links
        // wr.write( p1.getId() + "\t" + p2.getId() + "\t" + gene1String + "\t" + gene2String + "\t" + nf.format( w
        // ) + "\n" );

    }

    wr.write("# totalLinks:" + keptLinksCount + "\n");
    wr.write("# printedLinks:" + buf.size() + "\n");
    wr.write("# skippedDueToHighNodeDegree:" + skippedDueToDegree + "\n");

    for (String line : buf) {// write links to file
        wr.write(line);
    }

    if (la.getConfig().isSubsetUsed()) {// subset option activated
        LinkAnalysisServiceImpl.log.info("Done, " + keptLinksCount + "/" + links.size() + " links kept, "
                + buf.size() + " links printed");
        // wr.write("# Amount of links before subsetting/after subsetting: " + links.size() + "/" + numPrinted +
        // "\n" );
    } else {
        LinkAnalysisServiceImpl.log.info("Done, " + keptLinksCount + "/" + links.size()
                + " links printed (some may have been filtered)");
    }
    wr.flush();

}

From source file:com.nadmm.airports.wx.MetarFragment.java

protected void showMetar(Intent intent) {
    if (getActivity() == null) {
        // Not ready to do this yet
        return;/*from w  w  w.  j ava 2 s .com*/
    }

    Metar metar = (Metar) intent.getSerializableExtra(NoaaService.RESULT);
    if (metar == null) {
        return;
    }

    View detail = findViewById(R.id.wx_detail_layout);
    LinearLayout layout = (LinearLayout) findViewById(R.id.wx_status_layout);
    layout.removeAllViews();
    TextView tv = (TextView) findViewById(R.id.status_msg);
    if (!metar.isValid) {
        tv.setVisibility(View.VISIBLE);
        layout.setVisibility(View.VISIBLE);
        tv.setText("Unable to get METAR for this location");
        addRow(layout, "This could be due to the following reasons:");
        addBulletedRow(layout, "Network connection is not available");
        addBulletedRow(layout, "ADDS does not publish METAR for this station");
        addBulletedRow(layout, "Station is currently out of service");
        addBulletedRow(layout, "Station has not updated the METAR for more than 3 hours");
        detail.setVisibility(View.GONE);
        stopRefreshAnimation();
        setFragmentContentShown(true);
        return;
    } else {
        tv.setText("");
        tv.setVisibility(View.GONE);
        layout.setVisibility(View.GONE);
        detail.setVisibility(View.VISIBLE);
    }

    tv = (TextView) findViewById(R.id.wx_station_info2);
    WxUtils.setFlightCategoryDrawable(tv, metar.flightCategory);

    tv = (TextView) findViewById(R.id.wx_age);
    tv.setText(TimeUtils.formatElapsedTime(metar.observationTime));

    // Raw Text
    tv = (TextView) findViewById(R.id.wx_raw_metar);
    tv.setText(metar.rawText);

    // Winds
    tv = (TextView) findViewById(R.id.wx_wind_label);
    layout = (LinearLayout) findViewById(R.id.wx_wind_layout);
    layout.removeAllViews();
    int visibility = View.GONE;
    if (metar.windSpeedKnots < Integer.MAX_VALUE) {
        showWindInfo(layout, metar);
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Visibility
    tv = (TextView) findViewById(R.id.wx_vis_label);
    layout = (LinearLayout) findViewById(R.id.wx_vis_layout);
    layout.removeAllViews();
    visibility = View.GONE;
    if (metar.visibilitySM < Float.MAX_VALUE) {
        if (metar.flags.contains(Flags.AutoReport) && metar.visibilitySM == 10) {
            addRow(layout, "10+ statute miles horizontal");
        } else {
            NumberFormat decimal2 = NumberFormat.getNumberInstance();
            decimal2.setMaximumFractionDigits(2);
            decimal2.setMinimumFractionDigits(0);
            addRow(layout,
                    String.format("%s statute miles horizontal", FormatUtils.formatNumber(metar.visibilitySM)));
        }
        if (metar.vertVisibilityFeet < Integer.MAX_VALUE) {
            addRow(layout, String.format("%s vertical", FormatUtils.formatFeetAgl(metar.vertVisibilityFeet)));
        }
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Weather
    layout = (LinearLayout) findViewById(R.id.wx_weather_layout);
    layout.removeAllViews();
    for (WxSymbol wx : metar.wxList) {
        addWeatherRow(layout, wx, metar.flightCategory);
    }

    // Sky Conditions
    tv = (TextView) findViewById(R.id.wx_sky_cond_label);
    layout = (LinearLayout) findViewById(R.id.wx_sky_cond_layout);
    layout.removeAllViews();
    visibility = View.GONE;
    if (!metar.skyConditions.isEmpty()) {
        for (SkyCondition sky : metar.skyConditions) {
            addSkyConditionRow(layout, sky, metar.flightCategory);
        }
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Temperature
    tv = (TextView) findViewById(R.id.wx_temp_label);
    layout = (LinearLayout) findViewById(R.id.wx_temp_layout);
    layout.removeAllViews();
    visibility = View.GONE;
    if (metar.tempCelsius < Float.MAX_VALUE && metar.dewpointCelsius < Float.MAX_VALUE) {
        addRow(layout, "Temperature", FormatUtils.formatTemperature(metar.tempCelsius));
        if (metar.dewpointCelsius < Float.MAX_VALUE) {
            addRow(layout, "Dew point", FormatUtils.formatTemperature(metar.dewpointCelsius));
            addRow(layout, "Relative humidity", String.format("%.0f%%", WxUtils.getRelativeHumidity(metar)));

            long denAlt = WxUtils.getDensityAltitude(metar);
            if (denAlt > mElevation) {
                addRow(layout, "Density altitude", FormatUtils.formatFeet(denAlt));
            }
        } else {
            addRow(layout, "Dew point", "n/a");
        }

        if (metar.maxTemp6HrCentigrade < Float.MAX_VALUE) {
            addRow(layout, "6-hour maximum", FormatUtils.formatTemperature(metar.maxTemp6HrCentigrade));
        }
        if (metar.minTemp6HrCentigrade < Float.MAX_VALUE) {
            addRow(layout, "6-hour minimum", FormatUtils.formatTemperature(metar.minTemp6HrCentigrade));
        }
        if (metar.maxTemp24HrCentigrade < Float.MAX_VALUE) {
            addRow(layout, "24-hour maximum", FormatUtils.formatTemperature(metar.maxTemp24HrCentigrade));
        }
        if (metar.minTemp24HrCentigrade < Float.MAX_VALUE) {
            addRow(layout, "24-hour minimum", FormatUtils.formatTemperature(metar.minTemp24HrCentigrade));
        }
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Pressure
    tv = (TextView) findViewById(R.id.wx_pressure_label);
    layout = (LinearLayout) findViewById(R.id.wx_pressure_layout);
    layout.removeAllViews();
    visibility = View.GONE;
    if (metar.altimeterHg < Float.MAX_VALUE) {
        addRow(layout, "Altimeter", FormatUtils.formatAltimeter(metar.altimeterHg));
        if (metar.seaLevelPressureMb < Float.MAX_VALUE) {
            addRow(layout, "Sea level pressure",
                    String.format("%s mb", FormatUtils.formatNumber(metar.seaLevelPressureMb)));
        }
        long presAlt = WxUtils.getPressureAltitude(metar);
        if (presAlt > mElevation) {
            addRow(layout, "Pressure altitude", FormatUtils.formatFeet(presAlt));
        }
        if (metar.pressureTend3HrMb < Float.MAX_VALUE) {
            addRow(layout, "3-hour tendency", String.format("%+.2f mb", metar.pressureTend3HrMb));
        }
        if (metar.presfr) {
            addRow(layout, "Pressure falling rapidly");
        }
        if (metar.presrr) {
            addRow(layout, "Pressure rising rapidly");
        }
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Precipitation
    tv = (TextView) findViewById(R.id.wx_precip_label);
    layout = (LinearLayout) findViewById(R.id.wx_precip_layout);
    layout.removeAllViews();
    if (metar.precipInches < Float.MAX_VALUE) {
        addRow(layout, "1-hour precipitation", String.format("%.2f\"", metar.precipInches));
    }
    if (metar.precip3HrInches < Float.MAX_VALUE) {
        addRow(layout, "3-hour precipitation", String.format("%.2f\"", metar.precip3HrInches));
    }
    if (metar.precip6HrInches < Float.MAX_VALUE) {
        addRow(layout, "6-hour precipitation", String.format("%.2f\"", metar.precip6HrInches));
    }
    if (metar.precip24HrInches < Float.MAX_VALUE) {
        addRow(layout, "24-hour precipitation", String.format("%.2f\"", metar.precip24HrInches));
    }
    if (metar.snowInches < Float.MAX_VALUE) {
        addRow(layout, "Snow depth", String.format("%.0f\"", metar.snowInches));
    }
    if (metar.snincr) {
        addRow(layout, "Snow is increasing rapidly");
    }
    visibility = layout.getChildCount() > 0 ? View.VISIBLE : View.GONE;
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Remarks
    tv = (TextView) findViewById(R.id.wx_remarks_label);
    layout = (LinearLayout) findViewById(R.id.wx_remarks_layout);
    layout.removeAllViews();
    for (Flags flag : metar.flags) {
        addBulletedRow(layout, flag.toString());
    }
    for (String remark : mRemarks) {
        addBulletedRow(layout, remark);
    }
    visibility = layout.getChildCount() > 0 ? View.VISIBLE : View.GONE;
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Fetch time
    tv = (TextView) findViewById(R.id.wx_fetch_time);
    tv.setText("Fetched on " + TimeUtils.formatDateTime(getActivity(), metar.fetchTime));
    tv.setVisibility(View.VISIBLE);

    stopRefreshAnimation();
    setFragmentContentShown(true);
}

From source file:voldemort.performance.benchmark.Benchmark.java

@SuppressWarnings("cast")
public long runTests(boolean runBenchmark) throws Exception {

    int localOpsCounts = 0;
    String label = null;/*w ww. ja v a 2 s  .c  om*/
    if (runBenchmark) {
        localOpsCounts = this.opsCount;
        label = new String("benchmark");
    } else {
        localOpsCounts = this.recordCount;
        label = new String("warmup");
    }
    Vector<Thread> threads = new Vector<Thread>();

    for (int index = 0; index < this.numThreads; index++) {
        VoldemortWrapper db = new VoldemortWrapper(storeClient, this.verifyRead && this.warmUpCompleted,
                this.ignoreNulls, this.localMode);
        WorkloadPlugin plugin = null;
        if (this.pluginName != null && this.pluginName.length() > 0) {
            Class<?> cls = Class.forName(this.pluginName);
            try {
                plugin = (WorkloadPlugin) cls.newInstance();
            } catch (IllegalAccessException e) {
                System.err.println("Class not accessible ");
                System.exit(1);
            } catch (InstantiationException e) {
                System.err.println("Class not instantiable.");
                System.exit(1);
            }
            plugin.setDb(db);
        }

        int opsPerThread = localOpsCounts / this.numThreads;
        // Make the last thread handle the remainder.
        if (index == this.numThreads - 1) {
            opsPerThread += localOpsCounts % this.numThreads;
        }

        threads.add(new ClientThread(db, runBenchmark, this.workLoad, opsPerThread,
                this.perThreadThroughputPerMs, this.verbose, plugin));
    }

    long startRunBenchmark = System.currentTimeMillis();
    for (Thread currentThread : threads) {
        currentThread.start();
    }

    StatusThread statusThread = null;
    if (this.statusIntervalSec > 0) {
        statusThread = new StatusThread(threads, this.statusIntervalSec, startRunBenchmark);
        statusThread.start();
    }

    for (Thread currentThread : threads) {
        try {
            currentThread.join();
        } catch (InterruptedException e) {
            if (this.verbose)
                e.printStackTrace();
        }
    }
    long endRunBenchmark = System.currentTimeMillis();

    if (this.statusIntervalSec > 0) {
        statusThread.interrupt();
    }

    // Print the output
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(4);
    nf.setGroupingUsed(false);

    System.out.println("[" + label + "]\tRunTime(ms): " + nf.format((endRunBenchmark - startRunBenchmark)));
    double throughput = Time.MS_PER_SECOND * ((double) localOpsCounts)
            / ((double) (endRunBenchmark - startRunBenchmark));
    System.out.println("[" + label + "]\tThroughput(ops/sec): " + nf.format(throughput));

    if (runBenchmark) {
        Metrics.getInstance().printReport(System.out);
    }
    return (endRunBenchmark - startRunBenchmark);
}

From source file:org.rythmengine.utils.S.java

/**
 * Format give data into currency using locale info from the engine specified
 * /*from   w  ww  .j a v  a 2 s.c o  m*/
 * <p>The method accept any data type. When <code>null</code> is found then 
 * <code>NullPointerException</code> will be thrown out; if an <code>Number</code>
 * is passed in, it will be type cast to <code>Number</code>; otherwise 
 * a <code>Double.valueOf(data.toString())</code> is used to find out
 * the number</p>
 *
 * @param template
 * @param data
 * @param currencyCode
 * @param locale
 * @return the currency
 */
public static String formatCurrency(ITemplate template, Object data, String currencyCode, Locale locale) {
    if (null == data)
        throw new NullPointerException();
    Number number;
    if (data instanceof Number) {
        number = (Number) data;
    } else {
        number = Double.parseDouble(data.toString());
    }
    if (null == locale)
        locale = I18N.locale(template);
    Currency currency = null == currencyCode ? Currency.getInstance(locale)
            : Currency.getInstance(currencyCode);
    NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
    numberFormat.setCurrency(currency);
    numberFormat.setMaximumFractionDigits(currency.getDefaultFractionDigits());
    String s = numberFormat.format(number);
    s = s.replace(currency.getCurrencyCode(), currency.getSymbol(locale));
    return s;
}

From source file:sadl.modellearner.rtiplus.SimplePDRTALearner.java

protected String getDuration(long start, long end) {

    final NumberFormat nf = NumberFormat.getInstance(Locale.US);
    nf.setMaximumFractionDigits(3);

    double dur = (end - start) / 1000.0;
    if (dur > 120.0) {
        dur = dur / 60.0;//from w  w w  .  jav a 2s .co  m
        if (dur > 120.0) {
            dur = dur / 60.0;
            if (dur > 48.0) {
                dur = dur / 24.0;
                return nf.format(dur) + "d";
            } else {
                return nf.format(dur) + "h";
            }
        } else {
            return nf.format(dur) + "m";
        }
    } else {
        return nf.format(dur) + "s";
    }
}

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

private void configureFormatter(NumberFormat formatter, Boolean isGroupingUsed, Number maxIntegerDigits,
        Number minIntegerDigits, Number maxFractionDigits, Number minFractionDigits) {
    if (isGroupingUsed != null)
        formatter.setGroupingUsed(isGroupingUsed.booleanValue());
    if (maxIntegerDigits != null)
        formatter.setMaximumIntegerDigits(maxIntegerDigits.intValue());
    if (minIntegerDigits != null)
        formatter.setMinimumIntegerDigits(minIntegerDigits.intValue());
    if (maxFractionDigits != null)
        formatter.setMaximumFractionDigits(maxFractionDigits.intValue());
    if (minFractionDigits != null)
        formatter.setMinimumFractionDigits(minFractionDigits.intValue());
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

/**
 * Converts the input as a number using java's number formatter to a string output.
 *///from ww  w. j  a  v a 2 s .  c  om
private String doConvertFromNumberToString(Map<String, Object> context, Object value, Class toType) {
    // XW-409: If the input is a Number we should format it to a string using the choosen locale and use java's numberformatter
    if (Number.class.isAssignableFrom(toType)) {
        NumberFormat numFormat = NumberFormat.getInstance(getLocale(context));
        if (isIntegerType(toType)) {
            numFormat.setParseIntegerOnly(true);
        }
        numFormat.setGroupingUsed(true);
        numFormat.setMaximumFractionDigits(99); // to be sure we include all digits after decimal seperator, otherwise some of the fractions can be chopped

        String number = numFormat.format(value);
        if (number != null) {
            return number;
        }
    }

    return null; // no number
}

From source file:ubic.gemma.apps.Blat.java

/**
 * @param querySequenceFile/*from  w  w  w.j  av  a  2s .  c  o  m*/
 * @param outputPath
 * @return processed results.
 */
private Collection<BlatResult> jniGfClientCall(final File querySequenceFile, final String outputPath,
        final int portToUse) throws IOException {
    try {
        log.debug("Starting blat run");

        FutureTask<Boolean> blatThread = new FutureTask<Boolean>(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                GfClientCall(host, Integer.toString(portToUse), seqDir, querySequenceFile.getPath(),
                        outputPath);
                return true;
            }
        });

        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(blatThread);
        executor.shutdown();

        // wait...
        StopWatch overallWatch = new StopWatch();
        overallWatch.start();

        while (!blatThread.isDone()) {
            try {
                Thread.sleep(BLAT_UPDATE_INTERVAL_MS);
            } catch (InterruptedException ie) {
                throw new RuntimeException(ie);
            }

            synchronized (outputPath) {
                File outputFile = new File(outputPath);
                Long size = outputFile.length();
                NumberFormat nf = new DecimalFormat();
                nf.setMaximumFractionDigits(2);
                String minutes = TimeUtil.getMinutesElapsed(overallWatch);
                log.info("BLAT output so far: " + nf.format(size / 1024.0) + " kb (" + minutes
                        + " minutes elapsed)");
            }

        }

        overallWatch.stop();
        String minutes = TimeUtil.getMinutesElapsed(overallWatch);
        log.info("Blat took a total of " + minutes + " minutes");

    } catch (UnsatisfiedLinkError e) {
        log.error(e, e);
        log.info("Falling back on exec()");
        this.execGfClient(querySequenceFile, outputPath, portToUse);
    }
    return this.processPsl(outputPath, null);
}