List of usage examples for java.text NumberFormat getNumberInstance
public static final NumberFormat getNumberInstance()
From source file:StopWatch.java
/** * Return a string with a table describing all tasks performed. * For custom reporting, call getTaskInfo() and use the task info directly. *//*from www. j a v a 2 s .co m*/ public String prettyPrint() { StringBuffer sb = new StringBuffer(shortSummary()); sb.append('\n'); if (!this.keepTaskList) { sb.append("No task info kept"); } else { TaskInfo[] tasks = getTaskInfo(); sb.append("-----------------------------------------\n"); sb.append("ms % Task name\n"); sb.append("-----------------------------------------\n"); NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumIntegerDigits(5); nf.setGroupingUsed(false); NumberFormat pf = NumberFormat.getPercentInstance(); pf.setMinimumIntegerDigits(3); pf.setGroupingUsed(false); for (int i = 0; i < tasks.length; i++) { sb.append(nf.format(tasks[i].getTimeMillis()) + " "); sb.append(pf.format(tasks[i].getTimeSeconds() / getTotalTimeSeconds()) + " "); sb.append(tasks[i].getTaskName() + "\n"); } } return sb.toString(); }
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();/*from w w w .ja v a2s .c om*/ 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.oonusave.coupon.MyMapStore.java
public double formatFraction(double d) { try {//ww w .ja v a2 s . c o m NumberFormat nf = NumberFormat.getNumberInstance(); nf.setGroupingUsed(false); // don't group by threes nf.setMinimumFractionDigits(5); nf.setMaximumFractionDigits(5); String sd = nf.format(d); return Double.valueOf(sd.trim()).doubleValue(); } catch (Exception e) { e.printStackTrace(); } return d; }
From source file:org.artifactory.webapp.wicket.page.search.BaseSearchPanel.java
public BaseSearchPanel(final Page parent, String id) { super(id);/*from www .ja va 2 s. com*/ AjaxUtils.refreshFeedback(); searchBorder = new WebMarkupContainer("searchBorder"); searchBorder.setOutputMarkupId(true); add(searchBorder); // Results table dataProvider = new SearchDataProvider(); dataProvider.setSort(new SortParam(RESULT_NAME_PROPERTY, true)); List<IColumn<ActionableSearchResult<T>>> columns = Lists.newArrayList(); addColumns(columns); final GroupableTable table = new GroupableTable<ActionableSearchResult<T>>("results", columns, dataProvider, ConstantValues.uiSearchMaxRowsPerPage.getInt()) { public String getSearchExpression() { return BaseSearchPanel.this.getSearchExpression(); } public String getSearchCount() { int maxResults = ConstantValues.searchMaxResults.getInt(); long fullResultsCount = searchResults.getFullResultsCount(); int queryLimit = ConstantValues.searchUserQueryLimit.getInt(); String searchExpression = BaseSearchPanel.this.getSearchExpression(); StringBuilder msg = new StringBuilder(); //Return this only if we limit the search results and don't return the full number of results found int rowCount = getRowCount(); if (isLimitSearchResults() && fullResultsCount > maxResults) { msg.append(rowCount).append(" out of ") .append(fullResultsCount == queryLimit ? "more than " : "").append(fullResultsCount) .append(" matches found for '").append(searchExpression).append("'"); } else if (isLimitSearchResults() && fullResultsCount == -1 && rowCount >= maxResults) { msg.append("Showing first ").append(rowCount).append(" matches found for '") .append(searchExpression).append("'"); } else if (searchExpression == null) { msg.append(rowCount).append(" matches found"); } else { msg.append(rowCount).append(" matches found for '").append(searchExpression).append("'"); } String timeStr = NumberFormat.getNumberInstance().format(searchResults.getTime()); msg.append(" (").append(timeStr).append(" ms)"); return msg.toString(); } @Override protected NavigationToolbarWithDropDown getDropDownNavToolbar() { return new NavigationToolbarWithDropDown(this, 0); } }; searchBorder.add(table); //Form Form form = new SecureForm("form"); form.setOutputMarkupId(true); searchBorder.add(form); addSearchComponents(form); //selected repo for search CompoundPropertyModel advancedModel = new CompoundPropertyModel<>(getSearchControls()); final AdvancedSearchPanel advancedPanel = new AdvancedSearchPanel("advancedPanel", advancedModel); form.add(advancedPanel); SearchAddon searchAddon = addons.addonByType(SearchAddon.class); SaveSearchResultsPanel saveSearchResultsPanel = searchAddon.getSaveSearchResultsPanel("saveResultsPanel", new PropertyModel(this, "searchResults.results"), this); saveSearchResultsPanel.init(); searchBorder.add(saveSearchResultsPanel); TitledAjaxSubmitLink searchButton = new TitledAjaxSubmitLink("submit", "Search", form) { @Override protected void onSubmit(AjaxRequestTarget target, Form form) { try { ComponentPersister.saveChildren(BaseSearchPanel.this); validateSearchControls(); onSearch(); fetchResults(parent); table.setCurrentPage(0); // scroll back to the first page target.add(searchBorder); advancedPanel.expandCollapseReposList(); } catch (IllegalArgumentException iae) { error(iae.getMessage()); } AjaxUtils.refreshFeedback(target); } @Override protected IAjaxCallDecorator getAjaxCallDecorator() { return new ImmediateAjaxIndicatorDecorator(); } }; addSearchButton(form, searchButton); form.add(new DefaultButtonBehavior(searchButton)); }
From source file:oscar.util.UtilMisc.java
public static String FloatToString(float value) { Float f = new Float(value); NumberFormat fmt = NumberFormat.getNumberInstance(); String s = fmt.format(f.doubleValue()); return s;//from ww w . ja v a 2s .co m }
From source file:org.angnysa.yaba.swing.BudgetFrame.java
private void buildReconciliationTable() { reconciliationModel = new ReconciliationTableModel(service); reconciliationTable = new JTable(reconciliationModel); reconciliationTable.setRowHeight((int) (reconciliationTable.getRowHeight() * 1.2)); reconciliationTable.setDefaultEditor(LocalDate.class, new CustomCellEditor(new JFormattedTextField(new JodaLocalDateFormat()))); reconciliationTable.setDefaultEditor(Double.class, new CustomCellEditor(new JFormattedTextField(NumberFormat.getNumberInstance()))); reconciliationTable.setDefaultRenderer(LocalDate.class, new FormattedTableCellRenderer(new JodaLocalDateFormat())); reconciliationTable.setDefaultRenderer(Double.class, new FormattedTableCellRenderer(TransactionAmountFormatFactory.getFormat())); reconciliationTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); reconciliationTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) .put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete"); //$NON-NLS-1$ reconciliationTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) .put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); //$NON-NLS-1$ reconciliationTable.getActionMap().put("delete", new AbstractAction() { //$NON-NLS-1$ private static final long serialVersionUID = 1L; @Override//from w ww. j a v a 2 s. c o m public void actionPerformed(ActionEvent e) { int row = reconciliationTable.getSelectedRow(); if (row >= 0) { reconciliationModel.deleteRow(row); } } }); transactionTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { int row = transactionTable.getSelectedRow(); if (row >= 0) { row = transactionTable.getRowSorter().convertRowIndexToModel(row); TransactionDefinition td = transactionModel.getTransactionForRow(row); if (td != null) { reconciliationModel.setCurrentTransactionId(td.getId()); } else { reconciliationModel.setCurrentTransactionId(-1); } } else { reconciliationModel.setCurrentTransactionId(-1); } } } }); }
From source file:edu.ucla.stat.SOCR.chart.demo.PieChartDemo4.java
protected JFreeChart createChart(PieDataset dataset) { // create the chart... JFreeChart chart = ChartFactory.createPieChart(chartTitle, // chart title dataset, // dataset !legendPanelOn, // include legend true, false);// w w w. ja va 2 s .c om // set the background color for the chart... chart.setBackgroundPaint(new Color(222, 222, 255)); PiePlot plot = (PiePlot) chart.getPlot(); plot.setBackgroundPaint(Color.white); plot.setCircular(true); for (int i = 0; i < pulloutFlag.length; i++) { //System.out.println("\""+pulloutFlag[i]+"\""); if (isPullout(i)) { Comparable key = dataset.getKey(i); plot.setExplodePercent(key, 0.30); } } plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} = {2}", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance())); plot.setNoDataMessage("No data available"); if (rotateOn) { Rotator rotator = new Rotator(plot); rotator.start(); } setCategorySummary(dataset); return chart; }
From source file:com.hangum.tadpole.rdb.core.editors.main.composite.direct.SQLResultLabelProvider.java
/** * ?? , ??.//ww w . j a v a 2 s .co m * * @param value * @return */ private static String addComma(Object value) { if (value == null) return PublicTadpoleDefine.DEFINE_NULL_VALUE; try { NumberFormat nf = NumberFormat.getNumberInstance(); return nf.format(Double.parseDouble(value.toString())); } catch (Exception e) { // ignore exception } return value.toString(); }
From source file:FormattedTextFieldDemo.java
private void setUpFormats() { amountFormat = NumberFormat.getNumberInstance(); percentFormat = NumberFormat.getNumberInstance(); percentFormat.setMinimumFractionDigits(3); paymentFormat = NumberFormat.getCurrencyInstance(); }
From source file:org.jcryptool.visual.verifiablesecretsharing.views.ReconstructionChartComposite.java
/** * Creates a chart.// ww w . j a v a2s . co m * * @param dataset * the data for the chart. * * @return a chart. */ private JFreeChart createChart(final XYDataset dataset) { // create the chart... final JFreeChart chart = ChartFactory.createXYLineChart("", // chart // title "", // x axis label "", // y axis label dataset, // data PlotOrientation.VERTICAL, true, // include legend false, // tooltips false // urls ); // XYSplineRenderer -- show data points XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinePaint(Color.white); final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); // show no line renderer.setSeriesLinesVisible(0, false); renderer.setSeriesLinesVisible(3, false); // show no points renderer.setSeriesShapesVisible(1, false); // set range of axis NumberAxis domain = (NumberAxis) plot.getDomainAxis(); domain.setRange(-0.1, playerID[playerID.length - 1] + 0.1); domain.setTickUnit(new NumberTickUnit(1)); domain.setVerticalTickLabels(false); // display value NumberFormat format = NumberFormat.getNumberInstance(); format.setMaximumFractionDigits(0); XYItemLabelGenerator generator = new StandardXYItemLabelGenerator( StandardXYItemLabelGenerator.DEFAULT_ITEM_LABEL_FORMAT, format, format); renderer.setBaseItemLabelGenerator(generator); renderer.setBaseItemLabelsVisible(true); plot.setRenderer(renderer); return chart; }