List of usage examples for java.text NumberFormat setMaximumFractionDigits
public void setMaximumFractionDigits(int newValue)
From source file:adalid.util.meta.sql.MetaFolderSql.java
public MetaFolderSql(String path) { NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumFractionDigits(1);//from w w w . java2 s . com nf.setMaximumFractionDigits(2); logger.info("max-file-size=" + nf.format(MAX_FILE_SIZE_MEGAS) + "MB"); rootFolder = PropertiesHandler.getRootFolder(); if (rootFolder == null) { throw new RuntimeException("root folder is missing or invalid"); } rootFolderPath = Paths.get(rootFolder.getPath()); logger.info("root-folder=" + rootFolderPath); if (path == null) { throw new IllegalArgumentException("null folder path"); } else { File file = new File(path); if (file.isAbsolute()) { metaFolder = file; } else { metaFolder = new File(rootFolder.getAbsolutePath(), path); } } metaFolderPath = Paths.get(metaFolder.getPath()); logger.info("meta-folder=" + metaFolderPath); if (metaFolder.isDirectory()) { if (metaFolder.isHidden()) { throw new IllegalArgumentException(metaFolderPath + " is a hidden directory"); } } else { throw new IllegalArgumentException(metaFolderPath + " is not a directory"); } baseFolder = metaFolder.getParentFile(); baseFolderPath = Paths.get(baseFolder.getPath()); logger.info("base-folder=" + baseFolderPath); files = new TreeMap<>(); folders = new TreeMap<>(); fileTypes = new TreeMap<>(); metaFolderWrapper = new FolderWrapper(metaFolder); folders.put(getRelativeToBasePath(metaFolder), metaFolderWrapper); }
From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java
private void renderDayMarkers(long pStart, long pEnd, Graphics2D pG2D) { Date d = new Date(pStart); d = DateUtils.setHours(d, 0);//w w w . j a v a2 s. co m d = DateUtils.setMinutes(d, 0); d = DateUtils.setSeconds(d, 0); d = DateUtils.setMilliseconds(d, 0); for (long mark = d.getTime(); mark <= pEnd; mark += DateUtils.MILLIS_PER_HOUR) { int markerPos = Math.round((mark - pStart) / DateUtils.MILLIS_PER_MINUTE); pG2D.setColor(Color.YELLOW); pG2D.fillRect(markerPos, 20, 2, 10); pG2D.setColor(Color.WHITE); pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f)); pG2D.fillRect(markerPos - 5, 15, 12, 10); pG2D.setColor(Color.BLACK); Calendar cal = Calendar.getInstance(); cal.setTime(new Date(mark)); NumberFormat f = NumberFormat.getNumberInstance(); f.setMinimumIntegerDigits(2); f.setMaximumFractionDigits(2); pG2D.drawString(f.format(cal.get(Calendar.HOUR_OF_DAY)), markerPos - 5, 23); } long currentDay = d.getTime(); while (currentDay < pEnd) { currentDay += DateUtils.MILLIS_PER_DAY; int markerPos = Math.round((currentDay - pStart) / DateUtils.MILLIS_PER_MINUTE); pG2D.setColor(new Color(123, 123, 123)); pG2D.fillRect(markerPos, 15, 3, 30); SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy"); String dayLabel = f.format(currentDay); Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(dayLabel, pG2D); pG2D.setColor(Color.YELLOW); int labelWidth = (int) labelBounds.getWidth() + 5; pG2D.fillRect(markerPos - (int) Math.rint(labelWidth / 2), 15, labelWidth, 10); pG2D.setColor(Color.BLACK); pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f)); pG2D.drawString(dayLabel, markerPos - (int) Math.rint(labelWidth / 2) + 2, 23); } }
From source file:com.levien.audiobuffersize.AudioBufferSize.java
JitterMeasurement analyzeDrift(double[] arr, double forceRate) { final int startupSkip = 100; int n = arr.length / 4; // Do linear regression to find timing drift double xys = 0, xs = 0, ys = 0, x2s = 0; int count = n - startupSkip; for (int i = startupSkip; i < n; i++) { double x = i; double y = arr[i]; xys += x * y;/*from w w w . ja va 2s. c o m*/ xs += x; ys += y; x2s += x * x; } double beta = (count * xys - xs * ys) / (count * x2s - xs * xs); double jitRate = forceRate == 0 ? beta : forceRate; //double alpha = (ys - beta * xs) / count; double minJit = 0; double maxJit = 0; for (int i = startupSkip; i < n; i++) { double err = jitRate * i - arr[i]; if (i == startupSkip || err < minJit) minJit = err; if (i == startupSkip || err > maxJit) maxJit = err; } JitterMeasurement jm = new JitterMeasurement(); jm.rate = beta; jm.jitter = maxJit - minJit; NumberFormat f = NumberFormat.getInstance(); f.setMinimumFractionDigits(3); f.setMaximumFractionDigits(3); logUI("ms per tick = " + f.format(jm.rate * 1000) + "; jitter (lr) = " + f.format(jm.jitter * 1000)); return jm; }
From source file:net.sourceforge.fenixedu.presentationTier.renderers.inquiries.InquiryGroupResultsResumeRenderer.java
private void renderColoredTable(int absoluteScaleSize, QuestionResultsSummaryBean questionResultsSummaryBean, HtmlTableRow row, HtmlTableCell medianCell, int medianClass) { HtmlText medianText = new HtmlText("<b>" + questionResultsSummaryBean.getMedian().getValue() + "</b>"); medianText.setEscaped(false);/*from w w w. j av a2s .com*/ medianCell.setBody(medianText); medianCell.setClasses("x" + medianClass); int colClassesIter = absoluteScaleSize; for (InquiryResult inquiryResult : questionResultsSummaryBean.getAbsoluteScaleValues()) { HtmlTableCell absoluteValueCell = row.createCell(); absoluteValueCell.setBody(new HtmlText(inquiryResult.getValue())); absoluteValueCell.setClasses("x" + colClassesIter); colClassesIter--; } HtmlTableCell scaleCells = row.createCell(); final HtmlTable scaleTable = new HtmlTable(); scaleCells.setBody(scaleTable); HtmlTableRow scaleRow = scaleTable.createRow(); NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault()); numberFormat.setMaximumFractionDigits(2); String div = "<div class=\"graph-bar-1" + questionResultsSummaryBean.getScaleValues().size() + "-"; double scaleProportion = 100.0 / questionResultsSummaryBean.getScaleValues().size(); int iter = 1; int firstCell = 1; for (InquiryResult inquiryResult : questionResultsSummaryBean.getScaleValues()) { HtmlTableCell scaleCell = scaleRow.createCell(); Double value = Double.valueOf(inquiryResult.getValue()) * 100.0; int roundedValue = (int) StrictMath.round(value); String extraBarClass = ""; if (iter == firstCell) { if (roundedValue != 0) { extraBarClass = " first-bar"; } else { firstCell++; } } String finalDiv = div + iter + extraBarClass + "\">" + roundedValue + "%</div>"; if ((roundedValue / scaleProportion) <= proportionBar) { finalDiv = div + iter + extraBarClass + "\"></div>"; } HtmlText divText = new HtmlText(finalDiv); divText.setEscaped(false); scaleCell.setBody(divText); scaleCell.setStyle(roundedValue != 0 ? "width: " + roundedValue + "%;" : "display: none;"); iter++; } setLastBarCellClass(scaleRow); }
From source file:gov.nasa.arc.geocam.geocam.GeoCamMobile.java
private void updateLocation(Location location) { double lat, lon; int status;/* ww w . j a va 2s . com*/ if (location == null) { lat = 0.0; lon = 0.0; status = LocationProvider.TEMPORARILY_UNAVAILABLE; } else { mLocation = location; mLocationProvider = mLocation.getProvider(); status = LocationProvider.AVAILABLE; lat = mLocation.getLatitude(); lon = mLocation.getLongitude(); } NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(6); TextView latText = (TextView) findViewById(R.id.main_latitude_textview); TextView lonText = (TextView) findViewById(R.id.main_longitude_textview); latText.setText(nf.format(lat) + DEGREE_SYMBOL); lonText.setText(nf.format(lon) + DEGREE_SYMBOL); ((TextView) findViewById(R.id.main_location_provider_textview)).setText(mLocationProvider); TextView locationStatusText = ((TextView) findViewById(R.id.main_location_status_textview)); switch (status) { case LocationProvider.AVAILABLE: locationStatusText.setText("available"); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: locationStatusText.setText("unavailable"); break; case LocationProvider.OUT_OF_SERVICE: locationStatusText.setText("no service"); break; default: locationStatusText.setText("unknown"); break; } }
From source file:com.opendoorlogistics.studio.components.geocoder.SearchResultsPanel.java
private void setTableModel() { final NumberFormat formatter = DecimalFormat.getInstance(); formatter.setMaximumFractionDigits(4); // update table table.setModel(new AbstractTableModel() { @Override/*from www . j av a 2 s . c o m*/ public String getColumnName(int column) { switch (column) { case 0: return "Rank"; case 1: return "Address"; case 2: return "Latitude"; case 3: return "Longitude"; case 4: return "Class"; case 5: return "Type"; } throw new IndexOutOfBoundsException(); } public Class<?> getColumnClass(int columnIndex) { return String.class; } @Override public Object getValueAt(int rowIndex, int column) { SearchResultPoint pnt = model.getSearchResults().get(rowIndex); switch (column) { case 0: return Integer.toString(rowIndex + 1); case 1: return pnt.getAddress(); case 2: return formatter.format(pnt.getLatitude()); case 3: return formatter.format(pnt.getLongitude()); case 4: return pnt.getCls(); case 5: return pnt.getType(); } throw new IndexOutOfBoundsException(); } @Override public int getRowCount() { return model.getSearchResults() != null ? model.getSearchResults().size() : 0; } @Override public int getColumnCount() { return 6; } }); PackTableColumn.packAll(table, 6); if (table.getModel().getRowCount() > 0) { table.getSelectionModel().setSelectionInterval(0, 0); } readSelectedIntoModel(); }
From source file:com.oonusave.coupon.MyMapStore.java
public double formatFraction(double d) { try {//from www . j av a2s .com 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:ca.wumbo.doommanager.client.controller.ConsoleController.java
/** * Takes whatever is in the text field and submits it. *//*from ww w . j a v a 2 s . c o m*/ private void submitLineToConsole() { // Trim the string before using, also nulls shouldn't happen (but just in case). String text = textField.getText().trim().replace('\0', '?'); // Ignore empty lines. if (text.isEmpty()) return; // Remember what we submitted, most recent goes first. commandBuffer.add(text); // Reset due to submission of text. commandBufferIndex = commandBuffer.size(); // Handle commands. switch (text.toLowerCase()) { case "clear": textArea.clear(); break; case "connect": // Note: Debugging only. textArea.appendText("Starting connection to local host..." + System.lineSeparator()); Optional<SelectionKey> key = clientSelector.openTCPConnection( new InetSocketAddress("localhost", Server.DEFAULT_LISTEN_PORT), new NetworkReceiver() { @Override public void signalConnectionTerminated() { System.out.println("Test connection killed."); } @Override public void receiveData(byte[] data) { System.out.println("Got data: " + data.length + " = " + Arrays.toString(data)); } }); if (key.isPresent()) { SelectionKey k = key.get(); Platform.runLater(() -> { try { Thread.sleep(2000); clientSelector.writeData(k, new byte[] { 1, 2 }); System.out.println("Go forth..."); } catch (Exception e) { System.err.println("UGH"); e.printStackTrace(); } }); } textArea.appendText("Connection made = " + key.isPresent() + System.lineSeparator()); break; case "copy": try { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection stringSelection = new StringSelection(textArea.getText()); clipboard.setContents(stringSelection, stringSelection); textArea.appendText("Copied to clipboard." + System.lineSeparator()); } catch (Exception e) { textArea.appendText("Error: Unable to get system clipboard." + System.lineSeparator()); } break; case "exit": coreController.exit(); break; case "getconnections": int numKeys = clientSelector.getNumConnections(); textArea.appendText("There " + (numKeys != 1 ? "are " : "is ") + numKeys + " key" + (numKeys != 1 ? "s." : ".") + System.lineSeparator()); break; case "help": textArea.appendText("Commands:" + System.lineSeparator()); textArea.appendText(" clear - Clears the console" + System.lineSeparator()); textArea.appendText(" copy - Copies all the content to your clipboard" + System.lineSeparator()); textArea.appendText(" exit - Exits the program" + System.lineSeparator()); textArea.appendText(" getconnections - Lists the connections available" + System.lineSeparator()); textArea.appendText(" help - Shows this help" + System.lineSeparator()); textArea.appendText(" history - Prints command history for " + MAX_COMMANDS_REMEMBERED + " entries" + System.lineSeparator()); textArea.appendText(" memory - Get current memory statistics" + System.lineSeparator()); textArea.appendText(" version - Gets the version information" + System.lineSeparator()); break; case "history": if (commandBuffer.size() <= 1) { textArea.appendText("No history to display" + System.lineSeparator()); break; } textArea.appendText("History:" + System.lineSeparator()); for (int i = 0; i < commandBuffer.size() - 1; i++) textArea.appendText(" " + commandBuffer.get(i) + System.lineSeparator()); // Print everything but the last command (which was this). break; case "memory": NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); nf.setMinimumFractionDigits(2); long totalMem = Runtime.getRuntime().totalMemory(); long usedMem = totalMem - Runtime.getRuntime().freeMemory(); long maxMem = Runtime.getRuntime().maxMemory(); double megabyte = 1024.0 * 1024.0; textArea.appendText("Memory statistics:" + System.lineSeparator()); textArea.appendText( " Memory used: " + nf.format(Math.abs(((double) usedMem / (double) maxMem)) * 100.0) + "%" + System.lineSeparator()); textArea.appendText( " " + nf.format(usedMem / megabyte) + " mb (used memory)" + System.lineSeparator()); textArea.appendText( " " + nf.format(maxMem / megabyte) + " mb (max memory)" + System.lineSeparator()); break; // DEBUG case "startserver": if (Start.getParsedRuntimeArgs().isClientServer()) { if (!serverManager.isInitialized()) { try { textArea.appendText("Starting server on port " + Server.DEFAULT_LISTEN_PORT + "." + System.lineSeparator()); serverManager.initialize(); } catch (Exception e) { textArea.appendText("Unable to initialize server." + System.lineSeparator()); textArea.appendText(" " + e.getMessage() + System.lineSeparator()); } } if (serverManager.isInitialized()) { if (!serverManager.isRunning()) { textArea.appendText("Running server on port " + Server.DEFAULT_LISTEN_PORT + "." + System.lineSeparator()); try { new Thread(serverManager, "ClientConsoleServer").start(); textArea.appendText("Successfully set up server." + System.lineSeparator()); } catch (Exception e) { textArea.appendText("Error setting up server:" + System.lineSeparator()); textArea.appendText(" " + e.getMessage() + System.lineSeparator()); } } else { textArea.appendText("Server is already running." + System.lineSeparator()); } } else { textArea.appendText("Server not initialized, cannot run." + System.lineSeparator()); } } break; // DEBUG case "stopserver": if (Start.getParsedRuntimeArgs().isClientServer()) { if (serverManager.isInitialized() && serverManager.isRunning()) { serverManager.requestServerTermination(); textArea.appendText("Requested server termination." + System.lineSeparator()); } else { textArea.appendText( "Cannot stop server, it has not been initialized or started." + System.lineSeparator()); } } break; case "version": textArea.appendText(applicationTitle + " version: " + applicationVersion + System.lineSeparator()); break; default: textArea.appendText("Unknown command: " + text + System.lineSeparator()); textArea.appendText("Type 'help' for commands" + System.lineSeparator()); break; } textField.clear(); }
From source file:javacommon.excel.ExcelReader.java
/** * ???/* w w w . jav a 2s . c om*/ * * @param c ? * @return */ private String getCellStringFormatValue(Cell c) { if (c == null) { return ""; } String value = null; NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); nf.setMaximumFractionDigits(12); switch (c.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: value = String.valueOf(c.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(c)) { return DateFormatUtils.ISO_DATE_FORMAT.format(c.getDateCellValue()); } else if ("@".equals(c.getCellStyle().getDataFormatString())) { value = nf.format(c.getNumericCellValue()); } else if ("General".equals(c.getCellStyle().getDataFormatString())) { value = nf.format(c.getNumericCellValue()); } else if (ArrayUtils.contains(ExcelConstants.DATE_PATTERNS, c.getCellStyle().getDataFormatString())) { value = DateFormatUtils.format(HSSFDateUtil.getJavaDate(c.getNumericCellValue()), c.getCellStyle().getDataFormatString()); } else { value = nf.format(c.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: value = c.getStringCellValue(); break; case Cell.CELL_TYPE_FORMULA: return c.getCellFormula(); } return value == null ? "" : value.trim(); }
From source file:javacommon.excel.ExcelReader.java
/** * ???/* w ww . ja v a2 s . c o m*/ * * @param c ? * @return */ private String getCellStringValue(Cell c) { if (c == null) { return ""; } String value = null; NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); nf.setMaximumFractionDigits(12); switch (c.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: value = String.valueOf(c.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(c)) { return DateFormatUtils.ISO_DATE_FORMAT.format(c.getDateCellValue()); } else if ("@".equals(c.getCellStyle().getDataFormatString())) { value = nf.format(c.getNumericCellValue()); } else if ("General".equals(c.getCellStyle().getDataFormatString())) { value = nf.format(c.getNumericCellValue()); } else if (ArrayUtils.contains(ExcelConstants.DATE_PATTERNS, c.getCellStyle().getDataFormatString())) { value = DateFormatUtils.format(HSSFDateUtil.getJavaDate(c.getNumericCellValue()), c.getCellStyle().getDataFormatString()); } else { value = nf.format(c.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: value = c.getStringCellValue(); break; case Cell.CELL_TYPE_FORMULA: value = c.getCellFormula(); break; } return value == null ? "" : value.trim(); }