List of usage examples for java.text DecimalFormat format
public final String format(double number)
From source file:bigtweet.model.StudyingBeacons.java
/** * Extra ouput file to generate a chart * call plotBeaconStudy in R project to obtain chart *//* ww w . j a v a 2s . co m*/ private void generateBatchOuputForChart(JSONArray parametersValues, int parametersValuesIndex, double meanEndorsers) { JSONObject parameters = (JSONObject) parametersValues.get(parametersValuesIndex);//parameters JSONObject aux = new JSONObject(); aux.put("links", parameters.get("beaconLinksNumber")); aux.put("centrality", parameters.get("beaconLinksCentrality")); DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US); DecimalFormat df = new DecimalFormat("0.000", otherSymbols); aux.put("meanEndorsers", df.format(meanEndorsers)); JSONForChart.add(aux); //write json file FileWriter file; try { file = new FileWriter(batchOutputFileForChart); file.write(JSONForChart.toJSONString()); file.flush(); file.close(); } catch (Exception ex) { Logger.getLogger(BTSimBatch.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:eu.uqasar.util.UQasarUtil.java
/** * Round double to two decimals//from w w w . j a v a 2 s. c om * @param number * @return */ public static Double round(double number) { DecimalFormat df = new DecimalFormat("#,##"); df.setRoundingMode(RoundingMode.DOWN); String s = df.format(number); return Double.valueOf(s); }
From source file:com.yahoo.platform.yui.coverage.report.FileReport.java
/** * Returns the percentage of lines called. * @return The percentage of lines called. * @throws org.json.JSONException//from ww w .jav a2 s. co m */ public double getCalledLinePercentage() throws JSONException { DecimalFormat twoDForm = new DecimalFormat("#.##"); return Double .valueOf(twoDForm.format(((double) getCalledLineCount() / (double) getTotalLineCount()) * 100)); }
From source file:com.yahoo.platform.yui.coverage.report.FileReport.java
/** * Returns the percentage of functions called. * @return The percentage of functions called. * @throws org.json.JSONException//from w ww .j a v a2 s . co m */ public double getCalledFunctionPercentage() throws JSONException { DecimalFormat twoDForm = new DecimalFormat("#.##"); return Double.valueOf( twoDForm.format(((double) getCalledFunctionCount() / (double) getTotalFunctionCount()) * 100)); }
From source file:com.gym.controller.UsuarioController.java
public Collection<String> cargaPeso() { Collection<String> peso = new ArrayList<String>(); //Collection<Float> peso = new ArrayList<Float>(); //Float a = 40.0F; Double a = 40.0;/*from www . j a v a 2 s . c o m*/ DecimalFormat format = new DecimalFormat("0.0"); //for (a=40.0F; a<140.0F; a=a+0.1F) { for (a = 40.0; a < 140; a = a + 0.1) { format.format(a); peso.add(format.format(a)); } return peso; }
From source file:piazza.services.ingest.util.GeoJsonSerializer.java
private void writePointCoords(JsonGenerator jgen, Point p) throws IOException { jgen.writeStartArray();/*from w w w.ja v a 2s . c o m*/ DecimalFormat df = new DecimalFormat("#.#"); df.setMaximumFractionDigits(8); jgen.writeNumber(df.format(p.getX())); jgen.writeNumber(df.format(p.getY())); jgen.writeEndArray(); }
From source file:gda.gui.beans.PVScannableBean.java
@Override protected void refreshValues() { synchronized (this) { try {//from w w w . j a v a2 s . c o m // get the units Object unit = theScannable.getAttribute(PVScannable.UNITSATTRIBUTE); if (unit != null) { unitsString = unit.toString(); } else { unitsString = ""; } // generate the tooltip tooltipString = theScannable.getName() + " "; // display the current value Double currentPosition = ScannableUtils.getCurrentPositionArray(theScannable)[0]; if (isZeroSmallNumbers() && currentPosition < 0.0001) { DecimalFormat myFormat = new DecimalFormat(); myFormat.applyPattern("#####.###"); valueString = myFormat.format(currentPosition).trim(); } else { valueString = String.format("%5.3g", currentPosition).trim(); } } catch (DeviceException e) { logger.error("Exception while trying to move " + scannableName + ": " + e.getMessage()); } } }
From source file:com.unicornlabs.kabouter.reporting.PowerReport.java
public static void GeneratePowerReport(Date startDate, Date endDate) { try {//from w w w . java 2 s .co m Historian theHistorian = (Historian) BusinessObjectManager.getBusinessObject(Historian.class.getName()); ArrayList<String> powerLogDeviceIds = theHistorian.getPowerLogDeviceIds(); Document document = new Document(PageSize.A4, 50, 50, 50, 50); File outputFile = new File("PowerReport.pdf"); outputFile.createNewFile(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); document.add(new Paragraph("Power Report for " + startDate.toString() + " to " + endDate.toString())); document.newPage(); DecimalFormat df = new DecimalFormat("#.###"); for (String deviceId : powerLogDeviceIds) { ArrayList<Powerlog> powerlogs = theHistorian.getPowerlogs(deviceId, startDate, endDate); double total = 0; double max = 0; Date maxTime = startDate; double average = 0; XYSeries series = new XYSeries(deviceId); XYDataset dataset = new XYSeriesCollection(series); for (Powerlog log : powerlogs) { total += log.getPower(); if (log.getPower() > max) { max = log.getPower(); maxTime = log.getId().getLogtime(); } series.add(log.getId().getLogtime().getTime(), log.getPower()); } average = total / powerlogs.size(); document.add(new Paragraph("\nDevice: " + deviceId)); document.add(new Paragraph("Average Power Usage: " + df.format(average))); document.add(new Paragraph("Maximum Power Usage: " + df.format(max) + " at " + maxTime.toString())); document.add(new Paragraph("Total Power Usage: " + df.format(total))); //Create a custom date axis to display dates on the X axis DateAxis dateAxis = new DateAxis("Date"); //Make the labels vertical dateAxis.setVerticalTickLabels(true); //Create the power axis NumberAxis powerAxis = new NumberAxis("Power"); //Set both axes to auto range for their values powerAxis.setAutoRange(true); dateAxis.setAutoRange(true); //Create the tooltip generator StandardXYToolTipGenerator ttg = new StandardXYToolTipGenerator("{0}: {2}", new SimpleDateFormat("yyyy/MM/dd HH:mm"), NumberFormat.getInstance()); //Set the renderer StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES, ttg, null); //Create the plot XYPlot plot = new XYPlot(dataset, dateAxis, powerAxis, renderer); //Create the chart JFreeChart myChart = new JFreeChart(deviceId, JFreeChart.DEFAULT_TITLE_FONT, plot, true); PdfContentByte pcb = writer.getDirectContent(); PdfTemplate tp = pcb.createTemplate(480, 360); Graphics2D g2d = tp.createGraphics(480, 360, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, 480, 360); myChart.draw(g2d, r2d); g2d.dispose(); pcb.addTemplate(tp, 0, 0); document.newPage(); } document.close(); JOptionPane.showMessageDialog(null, "Report Generated."); Desktop.getDesktop().open(outputFile); } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(null, "Unable To Open File For Writing, Make Sure It Is Not Currently Open"); } catch (IOException ex) { Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex); } catch (DocumentException ex) { Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.cisco.dvbu.ps.common.util.jdbcapi.JdbcConnector.java
/** * Creates a java.sql.Connection to a CIS server based on server.xml configuration * /*from w ww . j a v a2 s . c o m*/ * @param serverId serverId in servers.xml * @param pathToServersXML path to servers.xml * @param pubDs published datasource to connect to. * * @return java.sql.Connection established JDBC connection * @throws CompositeException */ public Connection connectToCis(CompositeServer cisServerConfig, String pubDs) throws CompositeException { String url = null; Connection conn = null; // Validate input: try { validateCisConnectionParams(cisServerConfig); } catch (CompositeException e) { throw e; } // Get config values: String host = cisServerConfig.getHostname(); String jdbcPort = new Integer((cisServerConfig.getPort() + 1)).toString(); // String cisDomain = cisServerConfig.getDomain(); String userName = cisServerConfig.getUser(); String userPwd = CommonUtils.decrypt(cisServerConfig.getPassword()); long startTime = System.currentTimeMillis(); if (logger.isDebugEnabled()) { logger.debug("Started establishing JDBC connection to CIS server " + host + ":" + jdbcPort); } try { Class.forName("cs.jdbc.driver.CompositeDriver"); url = "jdbc:compositesw:dbapi@" + host + ":" + jdbcPort + "?domain=" + cisDomain + "&dataSource=" + pubDs; // e.g. "system"; conn = DriverManager.getConnection(url, userName, userPwd); } catch (ClassNotFoundException e) { logger.error("Problem loading jdbc driver:\n", e); throw new CompositeException("Problem loading jdbc driver:\n" + e.getMessage()); } catch (Exception e) { logger.error("Exception caught: \n", e); throw new CompositeException("Exception caught:\n" + e.getMessage()); } long endTime = System.currentTimeMillis(); DecimalFormat threeDForm = new DecimalFormat("#.###"); double elapsedTime = Double.valueOf(threeDForm.format((0.001 * (endTime - startTime)))); if (logger.isDebugEnabled()) { logger.debug("CIS connection was established in " + elapsedTime + " seconds for database " + pubDs); } return conn; }
From source file:com.exilant.eGov.src.reports.GeneralLedgerReport.java
public static StringBuffer numberToString(final String strNumberToConvert) { String strNumber = "", signBit = ""; if (strNumberToConvert.startsWith("-")) { strNumber = "" + strNumberToConvert.substring(1, strNumberToConvert.length()); signBit = "-"; } else/*from ww w .j ava 2 s . co m*/ strNumber = "" + strNumberToConvert; final DecimalFormat dft = new DecimalFormat("##############0.00"); final String strtemp = "" + dft.format(Double.parseDouble(strNumber)); StringBuffer strbNumber = new StringBuffer(strtemp); final int intLen = strbNumber.length(); for (int i = intLen - 6; i > 0; i = i - 2) strbNumber.insert(i, ','); if (signBit.equals("-")) strbNumber = strbNumber.insert(0, "-"); return strbNumber; }