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.rockhoppertech.music.Note.java

public String getString() {
    final NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);//from  ww  w  . jav  a  2 s  . co  m
    nf.setMaximumIntegerDigits(3);
    // nf.setMinimumIntegerDigits(3);
    PitchFormat pf = PitchFormat.getInstance();
    return String.format("%s,%s,%s", pf.format(pitch).trim(), nf.format(startBeat),
            DurationParser.getDurationString(duration));
}

From source file:org.jactr.entry.iterative.IterativeMain.java

public void iteration(final int index, int total, Document environment, URL envURL,
        final Collection<IIterativeRunListener> listeners, final PrintWriter log)
        throws TerminateIterativeRunException {

    ExecutorServices.initialize();/*ww w . jav  a 2s . co m*/

    if (LOGGER.isDebugEnabled()) {
        long totalMem = Runtime.getRuntime().totalMemory();
        long freeMem = Runtime.getRuntime().freeMemory();
        LOGGER.debug("Running iteration " + index + "/" + total + " [" + freeMem / 1024 + "k free : "
                + (totalMem - freeMem) / 1024 + "k used of " + totalMem / 1024 + "k]");
    }

    for (IIterativeRunListener listener : listeners)
        try {
            listener.preLoad(index, total);
        } catch (Exception e) {
            LOGGER.error("listener " + listener + " threw an exception ", e);
        }

    /*
     * first we use the environment to load all the model descriptors
     */
    EnvironmentParser ep = new EnvironmentParser();
    Collection<CommonTree> modelDescriptors = ep.getModelDescriptors(environment, envURL);

    for (IIterativeRunListener listener : listeners)
        try {
            listener.preBuild(index, total, modelDescriptors);
        } catch (TerminateIterativeRunException tire) {
            throw tire;
        } catch (Exception e) {
            LOGGER.error("listener " + listener + " threw an exception ", e);
        }

    /*
     * now we actually do that vodoo that we do to set up the environment this
     * will build the models, instruments, and set up common reality..
     */
    ep.process(environment, modelDescriptors);

    modelDescriptors.clear();

    ACTRRuntime runtime = ACTRRuntime.getRuntime();

    Collection<IModel> models = runtime.getModels();

    for (IModel model : models)
        model.addListener(new ModelListenerAdaptor() {

            long startTime = 0;

            long simStartTime = 0;

            boolean closed = false;

            @Override
            public void modelStarted(ModelEvent event) {
                startTime = event.getSystemTime();
                simStartTime = (long) (event.getSimulationTime() * 1000);
            }

            protected String header(ModelEvent event) {
                StringBuilder sb = new StringBuilder("  <model name=\"");
                sb.append(event.getSource()).append("\" simulated=\"");
                sb.append(duration(simStartTime, (long) (event.getSimulationTime() * 1000)));
                sb.append("\" actual=\"");
                sb.append(duration(startTime, event.getSystemTime()));
                sb.append("\" factor=\"");

                double factor = (event.getSimulationTime() * 1000 - simStartTime)
                        / (event.getSystemTime() - startTime);
                NumberFormat format = NumberFormat.getNumberInstance();
                format.setMaximumFractionDigits(3);
                sb.append(format.format(factor)).append("\"");
                return sb.toString();
            }

            @Override
            public void modelStopped(ModelEvent event) {
                if (!closed)
                    synchronized (log) {
                        log.println(header(event) + "/>");
                    }
            }

            @Override
            public void exceptionThrown(ModelEvent event) {
                synchronized (log) {
                    closed = true;
                    log.println(header(event) + ">");
                    event.getException().printStackTrace(log);
                    log.println("  </model>");

                    for (IIterativeRunListener listener : listeners)
                        try {
                            listener.exceptionThrown(index, event.getSource(), event.getException());
                        } catch (TerminateIterativeRunException tire) {

                        }

                    /*
                     * from here we try to stop the runtime, but do not block.. that
                     * would be disasterous
                     */
                    IController controller = ACTRRuntime.getRuntime().getController();
                    controller.stop();
                }
            }

        }, ExecutorServices.INLINE_EXECUTOR);

    for (IIterativeRunListener listener : listeners)
        try {
            listener.preRun(index, total, models);
        } catch (TerminateIterativeRunException tire) {
            throw tire;
        } catch (Exception e) {
            LOGGER.error("listener " + listener + " threw an exception ", e);
        }

    try {
        /*
         * start 'er up!
         */
        IController controller = runtime.getController();

        /*
         * we do the model check in case the listener is monkeying around with the
         * models (adding, removing) the controller will not ever complete if no
         * models are executed.
         */
        if (models.size() != 0)
            try {
                controller.start().get();
                controller.complete().get();
            } catch (InterruptedException ie) {
                LOGGER.error("Interrupted while waiting for completion", ie);
            }

        /*
         * all done - time to notify and clean up
         */
        for (IIterativeRunListener listener : listeners)
            try {
                listener.postRun(index, total, models);
            } catch (TerminateIterativeRunException tire) {
                throw tire;
            } catch (Exception e) {
                LOGGER.error("listener " + listener + " threw an exception ", e);
            }
    } catch (TerminateIterativeRunException tire) {
        throw tire;
    } catch (Throwable e) {
        throw new RuntimeException("Failed to run iteration " + index + " ", e);
    } finally {
        cleanUp(runtime);
    }
}

From source file:com.rockhoppertech.music.Note.java

/**
 * <code>toString</code>// w  w  w.  j a  v  a  2 s . c  om
 * 
 * @return a <code>String</code> value
 */
@Override
public String toString() {
    final StringBuilder sb = new StringBuilder();
    final NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);
    nf.setMaximumIntegerDigits(3);
    nf.setMinimumIntegerDigits(3);
    sb.append(this.getClass().getSimpleName()).append('[');
    sb.append("startBeat: ").append(nf.format(startBeat));
    sb.append(" pitch: ").append(pitch);
    sb.append(" dur: ").append(nf.format(duration));
    sb.append(" : ").append(getDurationString());

    sb.append(" endBeat: ").append(nf.format(endBeat));
    sb.append(" midinum: ").append(pitch.getMidiNumber());
    sb.append(" rest: ").append(rest);
    sb.append(']');
    return sb.toString();
}

From source file:org.mycore.datamodel.ifs.MCRAudioVideoExtender.java

/**
 * Returns the framerate formatted as a String, e. g. "25.0"
 * /*from w ww .j av a2 s  .com*/
 * @return the framerate formatted as a String, e. g. "25.0"
 */
public String getFrameRateFormatted() {
    // double r = (double)( Math.round( frameRate * 10.0 ) ) / 10.0;
    NumberFormat formatter = NumberFormat.getInstance(Locale.ROOT);
    formatter.setGroupingUsed(false);
    formatter.setMinimumIntegerDigits(2);
    formatter.setMinimumFractionDigits(1);
    formatter.setMaximumFractionDigits(1);
    return formatter.format(frameRate);
}

From source file:com.cypress.cysmart.BLEServiceFragments.CSCService.java

private void showCaloriesBurnt() {
    try {/*w  ww .j a  v  a2  s .co m*/
        Number numWeight = NumberFormat.getInstance().parse(weightString);
        weightInt = numWeight.floatValue();
        float caloriesBurntInt = (((showElapsedTime()) * weightInt) * 8);
        caloriesBurntInt = caloriesBurntInt / 1000;
        NumberFormat formatter = NumberFormat.getNumberInstance();
        formatter.setMinimumFractionDigits(4);
        formatter.setMaximumFractionDigits(4);
        String finalBurn = formatter.format(caloriesBurntInt);
        mCaloriesBurnt.setText(finalBurn);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:voldemort.server.protocol.hadoop.RestHadoopFetcher.java

/**
 * Function to copy a file from the given filesystem with a checksum of type
 * 'checkSumType' computed and returned. In case an error occurs during such
 * a copy, we do a retry for a maximum of NUM_RETRIES
 * //from  w ww . j  av a 2 s  .  c o m
 * @param rfs RestFilesystem used to copy the file
 * @param source Source path of the file to copy
 * @param dest Destination path of the file on the local machine
 * @param stats Stats for measuring the transfer progress
 * @param checkSumType Type of the Checksum to be computed for this file
 * @return A Checksum (generator) of type checkSumType which contains the
 *         computed checksum of the copied file
 * @throws IOException
 */
private CheckSum copyFileWithCheckSum(RestFileSystem rfs, String source, File dest, CopyStats stats,
        CheckSumType checkSumType) throws Throwable {
    CheckSum fileCheckSumGenerator = null;
    logger.info("Starting copy of " + source + " to " + dest);
    BufferedInputStream input = null;
    OutputStream output = null;

    for (int attempt = 0; attempt < maxAttempts; attempt++) {
        boolean success = true;
        long totalBytesRead = 0;
        boolean fsOpened = false;

        try {
            // Create a per file checksum generator
            if (checkSumType != null) {
                fileCheckSumGenerator = CheckSum.getInstance(checkSumType);
            }

            logger.info("Attempt " + attempt + " at copy of " + source + " to " + dest);

            input = new BufferedInputStream(rfs.openFile(source).getInputStream());
            fsOpened = true;

            output = new BufferedOutputStream(new FileOutputStream(dest));
            byte[] buffer = new byte[bufferSize];
            while (true) {
                int read = input.read(buffer);
                if (read < 0) {
                    break;
                } else {
                    output.write(buffer, 0, read);
                }

                // Update the per file checksum
                if (fileCheckSumGenerator != null) {
                    fileCheckSumGenerator.update(buffer, 0, read);
                }

                // Check if we need to throttle the fetch
                if (throttler != null) {
                    throttler.maybeThrottle(read);
                }

                stats.recordBytes(read);
                if (stats.getBytesSinceLastReport() > reportingIntervalBytes) {
                    NumberFormat format = NumberFormat.getNumberInstance();
                    format.setMaximumFractionDigits(2);
                    logger.info(stats.getTotalBytesCopied() / (1024 * 1024) + " MB copied at "
                            + format.format(stats.getBytesPerSecond() / (1024 * 1024)) + " MB/sec - "
                            + format.format(stats.getPercentCopied()) + " % complete, destination:" + dest);
                    if (this.status != null) {
                        this.status.setStatus(stats.getTotalBytesCopied() / (1024 * 1024) + " MB copied at "
                                + format.format(stats.getBytesPerSecond() / (1024 * 1024)) + " MB/sec - "
                                + format.format(stats.getPercentCopied()) + " % complete, destination:" + dest);
                    }
                    stats.reset();
                }
            }
            // at this point, we are done!
            logger.info("Completed copy of " + source + " to " + dest);
        } catch (Throwable te) {
            success = false;
            if (!fsOpened) {
                logger.error("Error while opening the file stream to " + source, te);
            } else {
                logger.error("Error while copying file " + source + " after " + totalBytesRead + " bytes.", te);
            }
            if (te.getCause() != null) {
                logger.error("Cause of error ", te.getCause());
            }
            te.printStackTrace();

            if (attempt < maxAttempts - 1) {
                logger.info("Will retry copying after " + retryDelayMs + " ms");
                sleepForRetryDelayMs();
            } else {
                logger.info("Fetcher giving up copy after " + maxAttempts + " attempts");
                throw te;
            }
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(input);
            if (success) {
                break;
            }
        }
        logger.info("Completed copy of " + source + " to " + dest);
    }
    return fileCheckSumGenerator;
}

From source file:org.mycore.datamodel.ifs.MCRAudioVideoExtender.java

/**
 * Returns the streaming bitrate formatted as a String, e. g. "1.3 MBit" or
 * "300 kBit".// w w w. ja va2 s.c o  m
 * 
 * @return the streaming bitrate formatted as a String
 */
public String getBitRateFormatted() {
    NumberFormat bitRateFormatter = NumberFormat.getInstance(Locale.ROOT);
    bitRateFormatter.setMinimumIntegerDigits(1);
    bitRateFormatter.setGroupingUsed(false);
    if (bitRate > 100 * 1024) {
        bitRateFormatter.setMaximumFractionDigits(2);
        double b = bitRate / (1024f * 1024f);
        return bitRateFormatter.format(b) + " MBit";
    }
    bitRateFormatter.setMaximumFractionDigits(1);
    double b = bitRate / 1024f;
    return bitRateFormatter.format(b) + " kBit";
}

From source file:br.ufrgs.enq.jcosmo.ui.COSMOSACDialog.java

private void rebuildSigmaProfiles() {
    if (listModel.getSize() == 0) {
        if (err == true) {
            err = false;/*from ww  w .java 2  s .c om*/
            return;
        }
        JOptionPane.showMessageDialog(this, "Select compounds.", "Error", JOptionPane.OK_OPTION);
        return;
    }

    int num = listModel.getSize();
    COSMOSACCompound[] c = new COSMOSACCompound[num];
    double[][] area = new double[num][];
    double[][] charge = new double[num][];
    XYSeriesCollection dataset = new XYSeriesCollection();

    for (int i = 0; i < num; i++) {
        try {
            c[i] = db.getComp((String) listModel.getElementAt(i));
        } catch (SQLException e1) {
            e1.printStackTrace();
            return;
        }
    }

    COSMOSAC cosmosac = (COSMOSAC) modelBox.getSelectedItem();
    try {
        cosmosac.setComponents(c);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

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

    for (int i = 0; i < num; i++) {

        if (c[i] == null)
            return;

        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        area[i] = c[i].area;
        charge[i] = c[i].charge;

        int n = charge[0].length;
        XYSeries comp = new XYSeries(c[i].name);

        // charges represent the center of the segments
        comp.add(charge[i][0], area[i][0]);
        for (int j = 1; j < n; ++j) {
            comp.add(charge[i][j] - (charge[i][j] - charge[i][j - 1]) / 2, area[i][j]);
        }

        double areaT = 0;
        double absSigmaAvg = 0;
        double sigmaAvg2 = 0;
        for (int j = 1; j < n; ++j) {
            areaT += area[i][j];
            absSigmaAvg += area[i][j] * Math.abs(charge[i][j]);
            sigmaAvg2 += area[i][j] * charge[i][j] * charge[i][j];
        }
        absSigmaAvg /= areaT;
        sigmaAvg2 /= areaT;
        comp.setKey(c[i].name + " (A=" + nf.format(areaT) + ", |sigma|=" + nf.format(absSigmaAvg * 1000)
                + ", |sigma|2=" + nf.format(sigmaAvg2 * 10000) + ")");

        dataset.addSeries(comp);
        sigmaProfilePlot.setRenderer(i, stepRenderer);
        sigmaProfilePlot.getRenderer().setSeriesStroke(i, new BasicStroke(2.5f));
    }
    sigmaProfilePlot.setDataset(dataset);

    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}

From source file:com.cypress.cysmart.BLEServiceFragments.CSCService.java

/**
 * Display live cycling data//w w  w. ja v  a 2s  . co  m
 */
private void displayLiveData(final ArrayList<String> csc_data) {
    if (csc_data != null) {
        weightString = mWeightEdittext.getText().toString();
        try {
            Number cycledDist = NumberFormat.getInstance().parse(csc_data.get(0));
            NumberFormat distformatter = NumberFormat.getNumberInstance();
            distformatter.setMinimumFractionDigits(2);
            distformatter.setMaximumFractionDigits(2);
            String distanceRanInt = distformatter.format(cycledDist);
            mDistanceRan.setText(distanceRanInt);
            mCadence.setText(csc_data.get(1));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (mCurrentTime == 0) {
            mGraphLastXValue = 0;
            mCurrentTime = Utils.getTimeInSeconds();
        } else {
            mPreviosTime = mCurrentTime;
            mCurrentTime = Utils.getTimeInSeconds();
            mGraphLastXValue = mGraphLastXValue + (mCurrentTime - mPreviosTime) / 1000;
        }
        try {
            float val = Float.valueOf(csc_data.get(1));
            mDataSeries.add(mGraphLastXValue, val);
            mChart.repaint();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

From source file:com.redhat.rhn.common.localization.LocalizationService.java

/**
 * Format the Number based on the locale and convert it to a String to
 * display. Use a specified number of fractional digits.
 * @param numberIn Number to format./*from   w  w w. java 2 s. co m*/
 * @param localeIn Locale to use for formatting.
 * @param fractionalDigits The maximum number of fractional digits to use.
 * @return String representation of given number in given locale.
 */
public String formatNumber(Number numberIn, Locale localeIn, int fractionalDigits) {
    NumberFormat nf = NumberFormat.getInstance(localeIn);
    nf.setMaximumFractionDigits(fractionalDigits);
    return getDebugVersionOfString(nf.format(numberIn));
}