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.att.aro.ui.view.overviewtab.TraceBenchmarkChartPanel.java

/**
 * Creates the plot data set from the current analysis
 * //  ww  w . j  ava2  s  .  c o m
 * @return CategoryDataset The plot data set for promotion ratio ,
 *         throughput and J/Kb.
 */
private CategoryDataset createDataset() {
    double throughputPct = 0;
    double jpkbPct = 0;
    double promotionRatioPct = 0;

    double kbps = 0;
    double jpkb = 0;
    double promo = 0;

    if (CommonHelper.isNotNull(traceBenchmarkData)) {

        throughputPct = traceBenchmarkData.getThroughputPct();
        jpkbPct = traceBenchmarkData.getJpkbPct();
        promotionRatioPct = traceBenchmarkData.getPromotionRatioPct();

        kbps = traceBenchmarkData.getKbps();
        jpkb = traceBenchmarkData.getJpkb();
        promo = traceBenchmarkData.getPromoRatioPercentail();
    }

    NumberFormat nFormat = NumberFormat.getNumberInstance();
    nFormat.setMaximumFractionDigits(1);
    nFormat.setMinimumFractionDigits(1);

    double[][] data = new double[2][3];
    data[0][0] = throughputPct;
    data[0][1] = jpkbPct;
    data[0][2] = promotionRatioPct;
    data[1][0] = 100.0 - throughputPct;
    data[1][1] = 100.0 - jpkbPct;
    data[1][2] = 100.0 - promotionRatioPct;
    return DatasetUtilities.createCategoryDataset(new Integer[] { 1, 2 }, new String[] {
            MessageFormat.format(ResourceBundleHelper.getMessageString("overview.traceoverview.throughput"),
                    nFormat.format(kbps)),
            MessageFormat.format(ResourceBundleHelper.getMessageString("overview.traceoverview.jpkb"),
                    nFormat.format(jpkb)),
            MessageFormat.format(ResourceBundleHelper.getMessageString("overview.traceoverview.promoratio"),
                    nFormat.format(promo)) },
            data);
}

From source file:org.apache.flex.utilities.converter.flash.FlashConverter.java

/**
 * This method generates those artifacts that resemble the framework part of the Flash SDK.
 *
 * @throws ConverterException/*from  w  w w. j av  a2  s .  c o m*/
 */
protected void generateFrameworkArtifacts() throws ConverterException {
    // Create a list of all libs that should belong to the Flash SDK runtime.
    final File directory = new File(rootSourceDirectory, "frameworks.libs.player".replace(".", File.separator));
    if (!directory.exists() || !directory.isDirectory()) {
        throw new ConverterException("Runtime directory does not exist.");
    }
    final List<File> playerVersions = new ArrayList<File>();
    final File[] versions = directory.listFiles();
    if ((versions != null) && (versions.length > 0)) {
        playerVersions.addAll(Arrays.asList(versions));

        // Generate artifacts for every jar in the input directories.
        for (final File versionDir : playerVersions) {
            final File playerglobalSwc = new File(versionDir, "playerglobal.swc");

            // Convert any version into a two-segment version number.
            final double playerVersion = Double.valueOf(versionDir.getName());
            final NumberFormat doubleFormat = NumberFormat.getInstance(Locale.US);
            doubleFormat.setMinimumFractionDigits(1);
            doubleFormat.setMaximumFractionDigits(1);
            final String version = doubleFormat.format(playerVersion);

            // Create an artifact for the player-global.
            final MavenArtifact playerglobal = new MavenArtifact();
            playerglobal.setGroupId("com.adobe.flash.framework");
            playerglobal.setArtifactId("playerglobal");
            playerglobal.setVersion(version);
            playerglobal.setPackaging("swc");
            playerglobal.addDefaultBinaryArtifact(playerglobalSwc);
            writeArtifact(playerglobal);
        }
    }
}

From source file:mx.edu.um.mateo.inventario.dao.impl.CancelacionDaoHibernate.java

@Override
public String getFolio(Almacen almacen) {
    Query query = currentSession()
            .createQuery("select f from Folio f where f.nombre = :nombre and f.almacen.id = :almacenId");
    query.setString("nombre", "CANCELACION");
    query.setLong("almacenId", almacen.getId());
    query.setLockOptions(LockOptions.UPGRADE);
    Folio folio = (Folio) query.uniqueResult();
    if (folio == null) {
        folio = new Folio("CANCELACION");
        folio.setAlmacen(almacen);//from  w  ww. jav a2 s . c om
        currentSession().save(folio);
        return getFolio(almacen);
    }
    folio.setValor(folio.getValor() + 1);
    java.text.NumberFormat nf = java.text.DecimalFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMinimumIntegerDigits(9);
    nf.setMaximumIntegerDigits(9);
    nf.setMaximumFractionDigits(0);
    StringBuilder sb = new StringBuilder();
    sb.append("C-");
    sb.append(almacen.getEmpresa().getOrganizacion().getCodigo());
    sb.append(almacen.getEmpresa().getCodigo());
    sb.append(almacen.getCodigo());
    sb.append(nf.format(folio.getValor()));
    return sb.toString();
}

From source file:org.pentaho.di.trans.steps.univariatestats.UnivariateStatsMetaTest.java

@Test
public void testGetFields() throws KettleStepException {
    UnivariateStatsMeta meta = new UnivariateStatsMeta();
    UnivariateStatsMetaFunction[] functions = univariateFunctionArrayFieldLoadSaveValidator.getTestObject();
    meta.setInputFieldMetaFunctions(functions);
    RowMetaInterface mockRowMetaInterface = mock(RowMetaInterface.class);
    final AtomicBoolean clearCalled = new AtomicBoolean(false);
    final List<ValueMetaInterface> valueMetaInterfaces = new ArrayList<ValueMetaInterface>();
    doAnswer(new Answer<Void>() {

        @Override/*ww  w  . jav a 2s .c  o  m*/
        public Void answer(InvocationOnMock invocation) throws Throwable {
            clearCalled.set(true);
            return null;
        }
    }).when(mockRowMetaInterface).clear();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            if (!clearCalled.get()) {
                throw new RuntimeException("Clear not called before adding value metas");
            }
            valueMetaInterfaces.add((ValueMetaInterface) invocation.getArguments()[0]);
            return null;
        }
    }).when(mockRowMetaInterface).addValueMeta(any(ValueMetaInterface.class));
    meta.getFields(mockRowMetaInterface, null, null, null, null, null, null);
    Map<String, Integer> valueMetas = new HashMap<String, Integer>();
    for (ValueMetaInterface vmi : valueMetaInterfaces) {
        valueMetas.put(vmi.getName(), vmi.getType());
    }
    for (UnivariateStatsMetaFunction function : functions) {
        if (function.getCalcN()) {
            assertContains(valueMetas, function.getSourceFieldName() + "(N)", ValueMetaInterface.TYPE_NUMBER);
        }
        if (function.getCalcMean()) {
            assertContains(valueMetas, function.getSourceFieldName() + "(mean)",
                    ValueMetaInterface.TYPE_NUMBER);
        }
        if (function.getCalcStdDev()) {
            assertContains(valueMetas, function.getSourceFieldName() + "(stdDev)",
                    ValueMetaInterface.TYPE_NUMBER);
        }
        if (function.getCalcMin()) {
            assertContains(valueMetas, function.getSourceFieldName() + "(min)", ValueMetaInterface.TYPE_NUMBER);
        }
        if (function.getCalcMax()) {
            assertContains(valueMetas, function.getSourceFieldName() + "(max)", ValueMetaInterface.TYPE_NUMBER);
        }
        if (function.getCalcMedian()) {
            assertContains(valueMetas, function.getSourceFieldName() + "(median)",
                    ValueMetaInterface.TYPE_NUMBER);
        }
        if (function.getCalcPercentile() >= 0) {
            NumberFormat pF = NumberFormat.getInstance();
            pF.setMaximumFractionDigits(2);
            String res = pF.format(function.getCalcPercentile() * 100);
            assertContains(valueMetas, function.getSourceFieldName() + "(" + res + "th percentile)",
                    ValueMetaInterface.TYPE_NUMBER);
        }
    }
}

From source file:net.sf.infrared.web.action.PerfDataCallTracesAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IllegalAccessException, InvocationTargetException {
    HttpSession session = request.getSession();

    TreeFactory treeFactory = null;/*from  w  w  w. ja va2s.  c  o m*/
    String apiName = request.getParameter("api");
    if (apiName != null) {
        session.setAttribute("api", apiName);
    }

    // This parameter corresponds to the actual layer name to
    // which the api belongs
    String actualLayerName = request.getParameter("layerName");
    if (actualLayerName != null) {
        session.setAttribute("layerName", actualLayerName);
    }

    String className = request.getParameter("ctx");

    if (className != null) {
        session.setAttribute("ctx", className);
    }

    // This parameter corresponds to hierarchical layer if the navigation
    // is in the context of the hierarchical layer. Else it corresponds to
    // the absolute layer.

    String type = request.getParameter("type");
    if (type != null) {
        session.setAttribute("type", type);
    }

    final PerformanceDataSnapshot perData = (PerformanceDataSnapshot) session.getAttribute("perfData");
    final String layerType = (String) session.getAttribute("layerType");

    AggregateOperationTree aggrOptree = perData.getStats().getTree();
    String hierarchicalLayerName = null;
    if (layerType.equals("hier")) {
        hierarchicalLayerName = type;
    }
    TreeNode mergedHead = TreeUtil.getMergedExecutionContextTreeNode(aggrOptree, apiName, actualLayerName,
            className, hierarchicalLayerName);

    if (mergedHead != null) {

        final long OVERALL_TIME = ((AggregateExecutionTime) mergedHead.getValue()).getTotalInclusiveTime();
        final NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);

        NodeToStringConverter nodeToStringConverterMergedTree = new NodeToStringConverter() {
            public String toString(AggregateExecutionTime aggApiTime) {
                StringBuffer display = new StringBuffer();
                if (OVERALL_TIME == 0) {
                    display.append(aggApiTime.getContext().toString()).append(" [ ").append(" Total Time = ")
                            .append(aggApiTime.getTotalInclusiveTime()).append(" Exclusive Time = ")
                            .append(aggApiTime.getTotalExclusiveTime()).append(" Count = ")
                            .append(aggApiTime.getExecutionCount()).append(" ] ");
                } else {
                    display.append(aggApiTime.getContext().toString()).append(" [ ")
                            .append(nf.format((aggApiTime.getTotalInclusiveTime() * 100.0) / OVERALL_TIME))
                            .append("% -").append(" Total Time = ").append(aggApiTime.getTotalInclusiveTime())
                            .append(" Exclusive Time = ").append(aggApiTime.getTotalExclusiveTime())
                            .append(" Count = ").append(aggApiTime.getExecutionCount()).append(" ] ");

                }
                return display.toString();
            }

            public String getHref(AggregateExecutionTime apiTime) {
                ExecutionContext ctx = apiTime.getContext();
                String name = ctx.getName();
                String layer = ctx.getLayer();
                String layerName = "";
                String temp = null;
                if (layerType.equals("abs")) {
                    layerName = ctx.getLayer();
                } else if (layerType.equals("hier")) {
                    layerName = apiTime.getLayerName();
                }

                try {
                    temp = "perfData_apiSumm_callTracesAction.do?" + "api=" + URLEncoder.encode(name, "UTF-8")
                            + "&type=" + layerName + "&ctx=" + ctx.getClass().getName() + "&layerName=" + layer;
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                return temp;
            }

            public boolean isContextRelative() {
                return false;
            }
        };

        String tree = "InfraTree";
        treeFactory = new TreeFactoryImpl(mergedHead, tree, nodeToStringConverterMergedTree);
    }

    AggregateExecutionTime[] mergedTreeJdbcSummaries = new AggregateExecutionTime[0];
    SqlStatistics[] mergedTreeSqlStatistics = new SqlStatistics[0];

    if (mergedHead != null) {
        mergedTreeJdbcSummaries = ViewUtil.getJDBCSummary(mergedHead);
        mergedTreeSqlStatistics = ViewUtil.getSqlStatistics(mergedHead);
    }

    ArrayList jdbcSummaries = new ArrayList();

    for (int i = 0; i < mergedTreeJdbcSummaries.length; i++) {
        AggrExecTimeFormBean formBean = new AggrExecTimeFormBean();
        BeanUtils.copyProperties(formBean, mergedTreeJdbcSummaries[i]);
        jdbcSummaries.add(formBean);
    }

    ArrayList sqlStatisticsByExec = new ArrayList();
    int n = 5;
    SqlStatistics[] topNQueriesByExecution = ViewUtil.getTopNQueriesByExecutionTime(mergedTreeSqlStatistics, n);

    for (int i = 0; i < topNQueriesByExecution.length; i++) {
        SqlStatisticsFormBean formBean = new SqlStatisticsFormBean();
        BeanUtils.copyProperties(formBean, topNQueriesByExecution[i]);
        sqlStatisticsByExec.add(formBean);
    }

    ArrayList sqlStatisticsByCount = new ArrayList();
    SqlStatistics[] topNQueriesByCount = ViewUtil.getTopNQueriesByCount(mergedTreeSqlStatistics, n);

    for (int i = 0; i < topNQueriesByCount.length; i++) {
        SqlStatisticsFormBean formBean = new SqlStatisticsFormBean();
        BeanUtils.copyProperties(formBean, topNQueriesByCount[i]);
        sqlStatisticsByCount.add(formBean);
    }

    // These have been put in the session because the expansion
    // and contraction of the tree cause a new request which does
    // go through the struts action. The page is directly called.

    session.setAttribute("mergedHead", mergedHead);
    session.setAttribute("jdbcSummaries", jdbcSummaries);
    session.setAttribute("sqlStatisticsByExec", sqlStatisticsByExec);
    session.setAttribute("sqlStatisticsByCount", sqlStatisticsByCount);

    session.setAttribute("treeFactory", treeFactory);
    return mapping.findForward("repeat");
}

From source file:ubic.gemma.core.analysis.preprocess.filter.RowLevelFilter.java

private void logInfo(int numRows, List<CompositeSequence> kept) {
    if (kept.size() == 0) {
        RowLevelFilter.log.warn("All rows filtered out!");
        return;/*  w w w .  j  a v a  2  s .c o m*/
    }

    if (RowLevelFilter.log.isDebugEnabled()) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);

        double fracFiltered = (double) (numRows - kept.size()) / numRows;

        RowLevelFilter.log.debug(
                "There are " + kept.size() + " rows left after " + this.method + " filtering. Filtered out "
                        + (numRows - kept.size()) + " rows " + nf.format(100 * fracFiltered) + "%");
    }
}

From source file:ro.cs.cm.common.Tools.java

public String getDoubleWithoutComma(double number) {
    Locale localeRo = new Locale("ro", "RO", "");
    NumberFormat nf = NumberFormat.getInstance(localeRo);
    nf.setMaximumFractionDigits(-1);
    nf.setGroupingUsed(false);//w w  w. j  av  a2  s  . co m
    String s = "000";
    s = nf.format(number);
    return s;
}

From source file:com.bdaum.zoom.gps.naming.geonaming.internal.GeoNamesService.java

@Override
public double getElevation(double lat, double lon) throws UnknownHostException, HttpException, IOException {
    NumberFormat usformat = NumberFormat.getInstance(Locale.US);
    usformat.setMaximumFractionDigits(5);
    usformat.setGroupingUsed(false);//from   w w  w  . j  ava2s  . com
    InputStream in = openGeonamesService(NLS.bind("http://api.geonames.org/srtm3?lat={0}&lng={1}", //$NON-NLS-1$
            usformat.format(lat), usformat.format(lon)));
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
        String readLine = reader.readLine();
        if (readLine == null)
            return Double.NaN;
        try {
            double v = Double.parseDouble(readLine);
            return (v < -32000) ? Double.NaN : v;
        } catch (NumberFormatException e) {
            return Double.NaN;
        }
    }
}

From source file:org.grouplens.lenskit.eval.traintest.TrainTestJob.java

@SuppressWarnings("PMD.AvoidCatchingThrowable")
private void runEvaluation() throws IOException, RecommenderBuildException {
    EventBus bus = task.getProject().getEventBus();
    bus.post(JobEvents.started(this));
    Closer closer = Closer.create();/*from w ww .j a va 2 s. c  om*/
    try {
        outputs = task.getOutputs().getPrefixed(algorithmInfo, dataSet);
        TableWriter userResults = outputs.getUserWriter();
        List<Object> outputRow = Lists.newArrayList();

        logger.info("Building {} on {}", algorithmInfo, dataSet);
        StopWatch buildTimer = new StopWatch();
        buildTimer.start();
        buildRecommender();
        buildTimer.stop();
        logger.info("Built {} in {}", algorithmInfo.getName(), buildTimer);

        logger.info("Measuring {} on {}", algorithmInfo.getName(), dataSet.getName());

        StopWatch testTimer = new StopWatch();
        testTimer.start();
        List<Object> userRow = Lists.newArrayList();

        List<MetricWithAccumulator<?>> accumulators = Lists.newArrayList();

        for (Metric<?> eval : outputs.getMetrics()) {
            accumulators.add(makeMetricAccumulator(eval));
        }

        LongSet testUsers = dataSet.getTestData().getUserDAO().getUserIds();
        final NumberFormat pctFormat = NumberFormat.getPercentInstance();
        pctFormat.setMaximumFractionDigits(2);
        pctFormat.setMinimumFractionDigits(2);
        final int nusers = testUsers.size();
        logger.info("Testing {} on {} ({} users)", algorithmInfo, dataSet, nusers);
        int ndone = 0;
        for (LongIterator iter = testUsers.iterator(); iter.hasNext();) {
            if (Thread.interrupted()) {
                throw new InterruptedException("eval job interrupted");
            }
            long uid = iter.nextLong();
            userRow.add(uid);
            userRow.add(null); // placeholder for the per-user time
            assert userRow.size() == 2;

            Stopwatch userTimer = Stopwatch.createStarted();
            TestUser test = getUserResults(uid);

            userRow.add(test.getTrainHistory().size());
            userRow.add(test.getTestHistory().size());

            for (MetricWithAccumulator<?> accum : accumulators) {
                List<Object> ures = accum.measureUser(test);
                if (ures != null) {
                    userRow.addAll(ures);
                }
            }
            userTimer.stop();
            userRow.set(1, userTimer.elapsed(TimeUnit.MILLISECONDS) * 0.001);
            if (userResults != null) {
                try {
                    userResults.writeRow(userRow);
                } catch (IOException e) {
                    throw new RuntimeException("error writing user row", e);
                }
            }
            userRow.clear();

            ndone += 1;
            if (ndone % 100 == 0) {
                testTimer.split();
                double time = testTimer.getSplitTime();
                double tpu = time / ndone;
                double tleft = (nusers - ndone) * tpu;
                logger.info("tested {} of {} users ({}), ETA {}", ndone, nusers,
                        pctFormat.format(((double) ndone) / nusers),
                        DurationFormatUtils.formatDurationHMS((long) tleft));
            }
        }
        testTimer.stop();
        logger.info("Tested {} in {}", algorithmInfo.getName(), testTimer);

        writeMetricValues(buildTimer, testTimer, outputRow, accumulators);
        bus.post(JobEvents.finished(this));
    } catch (Throwable th) {
        bus.post(JobEvents.failed(this, th));
        throw closer.rethrow(th, RecommenderBuildException.class);
    } finally {
        try {
            cleanup();
        } finally {
            outputs = null;
            closer.close();
        }
    }
}

From source file:org.onebusaway.android.ui.RegionsFragment.java

/**
 * Sets the text view that contains distance with units based on input parameters
 *
 * @param text     the TextView to be set
 * @param distance the distance to be used, in miles (for imperial) or kilometers (for metric)
 * @param units    the units to be used from strings.xml, either preferences_preferred_units_option_metric
 *                 or preferences_preferred_units_option_imperial
 *//*from ww w  . j a v a 2s  .  c  o  m*/
private void setDistanceTextView(TextView text, double distance, String units) {
    Resources r = getResources();
    NumberFormat fmt = NumberFormat.getInstance();
    if (fmt instanceof DecimalFormat) {
        fmt.setMaximumFractionDigits(1);
    }

    if (units.equalsIgnoreCase(getString(R.string.preferences_preferred_units_option_imperial))) {
        text.setText(r.getQuantityString(R.plurals.distance_miles, (int) distance, fmt.format(distance)));
    } else if (units.equalsIgnoreCase(getString(R.string.preferences_preferred_units_option_metric))) {
        text.setText(r.getQuantityString(R.plurals.distance_kilometers, (int) distance, fmt.format(distance)));
    }
}