List of usage examples for java.text DecimalFormat format
public final String format(double number)
From source file:context.ui.control.tabular.TabularViewController.java
private void initialTableData() { data.loadTableData();/*from w w w .j a v a 2 s .c om*/ // double minWidth = tableView.getWidth() / data.getHeaders().size(); tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); int index = 0; for (String header : data.getHeaders()) { final int j = index; TableColumn tableColumn = new TableColumn(header); tableColumn.setComparator(new Comparator<String>() { @Override public int compare(String s1, String s2) { if (NumberUtils.isNumber(s1) && NumberUtils.isNumber(s2)) { return Double.compare(Double.parseDouble(s1), Double.parseDouble(s2)); } return Collator.getInstance().compare(s1, s2); } }); tableColumn.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<List<String>, String>, ObservableValue<String>>() { public ObservableValue<String> call(TableColumn.CellDataFeatures<List<String>, String> p) { final String val = p.getValue().get(j); if (isRoundDoubles() && NumberUtils.isNumber(val) && val.contains(".")) { DecimalFormat df = new DecimalFormat("#.##"); Double d = Double.parseDouble(val); return new SimpleStringProperty(df.format(d)); } else { return new SimpleStringProperty(val); } } }); index++; tableView.getColumns().add(tableColumn); // if (index < data.getHeaders().size() - 1) { // tableColumn.setMinWidth(minWidth); // } // System.out.println("width=" + tableColumn.getMinWidth()); } System.out.println("columns Count:" + tableView.getColumns().size()); // which will make your table view dynamic // ObservableList<ObservableList> csvData = FXCollections.observableArrayList(); // // for (List<StringProperty> dataList : data.getRows()) { // ObservableList<String> row = FXCollections.observableArrayList(); // for (StringProperty rowData : dataList) { // row.add(rowData.get()); // } // csvData.add(row); // add each row to cvsData // } System.out.println("Rows Count=" + data.getRows().size()); tableView.setItems(data.getRows()); // finally add data to tableview System.out.println("after Rows Count=" + tableView.getItems().size()); }
From source file:com.haulmont.yarg.formatters.impl.AbstractFormatter.java
protected String formatValue(Object value, String parameterName, String fullParameterName, String stringFunction) {//from w w w .j a v a 2 s . c o m if (value == null) { return ""; } String valueString; String formatString = getFormatString(parameterName, fullParameterName); if (formatString != null) { if (value instanceof Number) { DecimalFormat decimalFormat = new DecimalFormat(formatString); valueString = decimalFormat.format(value); } else if (value instanceof Date) { SimpleDateFormat dateFormat = new SimpleDateFormat(formatString); valueString = dateFormat.format(value); } else if (value instanceof String && !formatString.startsWith("${")) {//do not use inliner alias as format string valueString = String.format(formatString, value); } else { valueString = value.toString(); } } else { valueString = defaultFormat(value); } if (stringFunction != null) { valueString = applyStringFunction(valueString, stringFunction); } return valueString; }
From source file:BaselinePlotGenerator.java
private JFreeChart createChart(String filename, NssBaseline nssBaseline) { XYSeries series = new XYSeries(""); float[] baselineValues = nssBaseline.getBaselineValues(); // plot subband values for (int i = 0; i < baselineValues.length; i++) { series.add(i, baselineValues[i]); }//from w ww . j av a2 s .com // add a final point at the end with a zero Y value, // to force the y axis to display full scale series.add(baselineValues.length, 0.0); XYDataset data = new XYSeriesCollection(series); String title = "SonATA Baseline"; String xAxisLabel = "Subband"; String yAxisLabel = "Power"; JFreeChart chart = ChartFactory.createXYLineChart(title, xAxisLabel, yAxisLabel, data, PlotOrientation.VERTICAL, false, // legend true, // tooltips false // urls ); String filenameBase = new File(filename).getName(); String subTitle1 = filenameBase; chart.addSubtitle(new TextTitle(subTitle1)); DecimalFormat freqFormatter = new DecimalFormat("0000.000 MHz "); String freqString = freqFormatter.format(nssBaseline.getCenterFreqMhz()); DecimalFormat bandwidthFormatter = new DecimalFormat("0.00 MHz "); String bandwidthString = bandwidthFormatter.format(nssBaseline.getBandwidthMhz()); String subTitle2 = "Center Freq: " + freqString + " Bandwidth: " + bandwidthString; chart.addSubtitle(new TextTitle(subTitle2)); // move the data off of the axes // by extending the minimum axis value XYPlot plot = (XYPlot) ((JFreeChart) chart).getPlot(); double axisMarginPercent = 0.02; NumberAxis valueAxis = (NumberAxis) plot.getRangeAxis(); valueAxis.setLowerBound(-1.0 * valueAxis.getUpperBound() * axisMarginPercent); valueAxis = (NumberAxis) plot.getDomainAxis(); valueAxis.setLowerBound(-1.0 * valueAxis.getUpperBound() * axisMarginPercent); return chart; }
From source file:vn.edu.vttu.ui.PanelStatiticsService.java
private void btnStatiticsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStatiticsActionPerformed SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String datetimeStart = formatter.format(dtFormDate.getDate()); Timestamp tsStart = Timestamp.valueOf(datetimeStart); String datetimeEnd = formatter.format(dtToDate.getDate()); Timestamp tsToDate = Timestamp.valueOf(datetimeEnd); tbResult.setModel(TableService.getStatiticsService(tsStart, tsToDate, ConnectDB.conn())); tbResult.getColumnModel().getColumn(4).setCellRenderer(new NumberCellRenderer()); tbResult.getTableHeader().setReorderingAllowed(false); showChart();//from w ww . j av a2 s. c o m int total = 0; for (int i = 0; i < tbResult.getRowCount(); i++) { int x = 0; try { x = Integer.parseInt(tbResult.getValueAt(i, 4).toString().replaceAll("\\.", "")); } catch (Exception e) { x = Integer.parseInt(tbResult.getValueAt(i, 4).toString().replaceAll(",", "")); } total = total + x; } DecimalFormat df = new DecimalFormat("#,###,###"); lbTotalPay.setText(df.format(total) + " VN?"); }
From source file:com.wabacus.util.Tools.java
public static String formatDouble(String srcString, String pattern) { try {//from ww w .ja v a 2 s . c om if (srcString == null || srcString.trim().equals("")) { return ""; } DecimalFormat df = new DecimalFormat(pattern); srcString = df.format(Double.parseDouble(srcString)); return srcString; } catch (Exception e) { log.error("" + pattern + "??" + srcString + "?", e); return srcString; } }
From source file:com.wabacus.util.Tools.java
public static String formatLong(String srcString, String pattern) { try {//from ww w . j a v a2 s .co m if (srcString == null || srcString.trim().equals("")) { return ""; } DecimalFormat df = new DecimalFormat(pattern); srcString = df.format(Long.parseLong(srcString)); return srcString; } catch (Exception e) { log.error("" + pattern + "??" + srcString + "?", e); return srcString; } }
From source file:delfos.main.managers.experiment.join.xml.AggregateResultsXML.java
private Map<String, Object> extractCaseResultsMapFromElement(Element caseStudy) { Map<String, Object> ret = new TreeMap<>(); Element aggregateValues = caseStudy.getChild(AGGREGATE_VALUES_ELEMENT_NAME); for (Element measureResult : aggregateValues.getChildren()) { if (measureResult.getName().equals(AreaUnderROC.class.getSimpleName()) || measureResult.getName().equals(AreaUnderRoc.class.getSimpleName())) { Element curveElement = measureResult .getChild(ConfusionMatricesCurveXML.CONFUSION_MATRIX_CURVE_ELEMENT_NAME); try { ConfusionMatricesCurve curve = ConfusionMatricesCurveXML .getConfusionMatricesCurve(curveElement); for (int index = 1; index < curve.size(); index++) { double precisionAt = curve.getPrecisionAt(index); DecimalFormat format = new DecimalFormat("000"); ret.put("Precision@" + format.format(index), precisionAt); if (index == 20) { break; }// www. j a v a 2 s . com } } catch (UnrecognizedElementException ex) { Logger.getLogger(AggregateResultsXML.class.getName()).log(Level.SEVERE, null, ex); } } if (measureResult.getName().equals(ParameterOwnerXML.PARAMETER_OWNER_ELEMENT_NAME)) { String measureName = measureResult.getAttributeValue("name"); String measureValue = measureResult.getAttributeValue("value"); ret.put(measureName, measureValue); } else { String measureName = measureResult.getName(); String measureValue = measureResult.getAttributeValue("value"); ret.put(measureName, measureValue); } } return ret; }
From source file:es.pode.gestorFlujo.presentacion.objetosPersonales.ObjetosPersonalesControllerImpl.java
/** * @see es.pode.gestorFlujo.presentacion.objetosPersonales.ObjetosPersonalesController#cargarODESPersonales(org.apache.struts.action.ActionMapping, es.pode.gestorFlujo.presentacion.objetosPersonales.CargarODESPersonalesForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//* www . j av a 2s . com*/ public final void cargarODESPersonales(ActionMapping mapping, es.pode.gestorFlujo.presentacion.objetosPersonales.CargarODESPersonalesForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { if (logger.isDebugEnabled()) logger.debug("Cargando objtos personales"); SrvPublicacionService publi = this.getSrvPublicacionService(); SrvLocalizadorService localizador = this.getSrvLocalizadorService(); TransicionVO[] odesPersonales = publi.obtenODEsCreadosPorUsuario(LdapUserDetailsUtils.getUsuario()); if (odesPersonales != null && odesPersonales.length > 0) { TransicionConTamainoVO[] odesTamaino = new TransicionConTamainoVO[odesPersonales.length]; String[] identificadoresOdesPersonales = new String[odesPersonales.length]; if (logger.isDebugEnabled()) logger.debug("Entramos en el mapeo"); for (int i = 0; i < odesPersonales.length; i++) { odesTamaino[i] = new TransicionConTamainoVO(); // this.getBeanMapper().map(odesPersonales[i], odesTamaino[i]);//Intentar hacer el mapeo de array a array!!!!!!!!!!!! // logger.debug("Hemos hecho el mapeo del elemento "+i+"del array"); odesTamaino[i].setComentarios(odesPersonales[i].getComentarios()); odesTamaino[i].setFecha(odesPersonales[i].getFecha()); odesTamaino[i].setIdODE(odesPersonales[i].getIdODE()); if (logger.isDebugEnabled()) logger.debug("El identificador del ODE:" + odesTamaino[i].getIdODE()); identificadoresOdesPersonales[i] = odesPersonales[i].getIdODE();//Los guardamos para hacer la consulta al localizador odesTamaino[i].setIdUsuario(odesPersonales[i].getIdUsuario()); odesTamaino[i].setTitulo(odesPersonales[i].getTitulo()); odesTamaino[i].setCompartir(odesPersonales[i].getCompartido()); } Long[] tamainoOdes = null; if (identificadoresOdesPersonales != null && identificadoresOdesPersonales.length > 0) { tamainoOdes = localizador.consultaEspacioLocalizadores(identificadoresOdesPersonales); } for (int i = 0; i < odesPersonales.length; i++) { if (tamainoOdes[i] != null) { if (logger.isDebugEnabled()) logger.debug("taminoOdes[i]" + tamainoOdes[i]); //Vamos a insertar le tamaino en MB,no en bytes; double div = (double) tamainoOdes[i] / (1024 * 1024); String pattern = "###.##"; java.text.DecimalFormat myFormatter = new java.text.DecimalFormat(pattern); String output = myFormatter.format(div); odesTamaino[i].setTamaino(output); if (logger.isDebugEnabled()) logger.debug("Tamaino del ODE con id:" + odesTamaino[i].getIdODE() + " con double [" + div + "] y su tamaino es:" + output); } else { odesTamaino[i].setTamaino("0"); if (logger.isDebugEnabled()) logger.debug( "Tamaino del ODE con id:" + odesTamaino[i].getIdODE() + " su tamaino es: 0"); } } if (logger.isDebugEnabled()) logger.debug("Hemos salido de calcular los tamaos"); form.setListaODESAsArray(odesTamaino); form.setIdUsuario(LdapUserDetailsUtils.getUsuario()); if (logger.isDebugEnabled()) logger.debug("Insertamos usuario"); form.setTotalSuma(totalTamainoOdes(tamainoOdes)); if (logger.isDebugEnabled()) logger.debug("Hacemos la suma " + form.getTotalSuma()); long cuota = LdapUserDetailsUtils.getCuota() != null ? LdapUserDetailsUtils.getCuota() : 0L; //Lo tendremos que recoger de soporte if (logger.isDebugEnabled()) logger.debug("Recogemos la cuota de soporte " + cuota); form.setPorcentajeMemoriaCubierta(procentajeCubierto(form.getTotalSuma(), cuota)); //La cuota ir en MB, no en bytes long divCuota = (long) cuota / (1024 * 1024); form.setCuotaUsuario(divCuota); form.setEspacioLibre(restanteTamaino(form.getTotalSuma(), cuota)); } else { if (logger.isDebugEnabled()) logger.debug("No tiene objetos personales"); form.setListaODESAsArray(odesPersonales); form.setIdUsuario(LdapUserDetailsUtils.getUsuario()); form.setTotalSuma(0L); form.setPorcentajeMemoriaCubierta(0); //La cuota debe ir en MB long divCuota = (long) ((LdapUserDetailsUtils.getCuota()) / (1024 * 1024)); form.setCuotaUsuario(divCuota); form.setEspacioLibre(LdapUserDetailsUtils.getCuota()); } } catch (Exception e) { logger.error("Error al obtener los objetos personales: " + e); throw new ValidatorException("{gestor.flujo.error.obtener.personales}"); } }
From source file:MiGA.motifStats.java
private String cell(double fl, int len) { String str = ""; if (fl != 0) { DecimalFormat round = new DecimalFormat("#.###"); String ele = round.format(fl); if (ele.length() == len) { return ele; } else if (ele.length() < len) { int rest = len - ele.length(); for (int i = 0; i < rest; i++) { str += " "; }/*ww w .j av a 2 s. c om*/ str += ele; return str; } else { for (int i = 0; i < len; i++) { str += "#"; } return str; } } else { for (int i = 0; i < len - 1; i++) { str += " "; } str += "0"; return str; } }
From source file:fr.paris.lutece.portal.web.upload.UploadFilter.java
/** * * @return the size of the request to display in the error message *//*w w w . j ava2s . co m*/ private String getDisplaySize() { long lSizeMax = getRequestSizeMax(); DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(); decimalFormat.applyPattern("#"); String strMessage = (lSizeMax >= KILO_BYTE) ? (String.valueOf(lSizeMax / KILO_BYTE)) : (decimalFormat.format(lSizeMax / KILO_BYTE)); return strMessage; }