List of usage examples for java.text DecimalFormat format
public final String format(double number)
From source file:es.pode.gestorFlujo.presentacion.objetosCompartidos.ObjetosCompartidosControllerImpl.java
/** * @see es.pode.gestorFlujo.presentacion.objetosCompartidos.ObjetosCompartidosController#cargarODESCompartidos(org.apache.struts.action.ActionMapping, es.pode.gestorFlujo.presentacion.objetosCompartidos.CargarODESCompartidosForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w. ja v a2s .c o m public final void cargarODESCompartidos(ActionMapping mapping, es.pode.gestorFlujo.presentacion.objetosCompartidos.CargarODESCompartidosForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { if (logger.isDebugEnabled()) logger.debug("Cargando objetos compartidos"); SrvPublicacionService publi = this.getSrvPublicacionService(); SrvLocalizadorService localizador = this.getSrvLocalizadorService(); SrvAdminUsuariosService admin = this.getSrvAdminUsuariosService(); TransicionAutorVO[] odes = null; try { String[] todosUsuariosGrupos = admin .obtenerListaUsuariosGrupoTrabajo(LdapUserDetailsUtils.getUsuario()); // // String[] todosUsuariosGrupos=new String[] {LdapUserDetailsUtils.getUsuario()}; if (todosUsuariosGrupos != null && todosUsuariosGrupos.length > 0) { logger.info("Obtenidos lista de usuarios de los grupos pertenecientes de usuario:[" + LdapUserDetailsUtils.getUsuario() + "Numero de usuarios:[" + todosUsuariosGrupos.length); odes = publi.obtenODEsCompartidosPorUsuarios(todosUsuariosGrupos); logger.info("Obtenidos odes de esos usuarios, numero de odes pendientes de publicacion [" + odes.length); } else { logger.info("Obtenidos lista de todos los ODES, pues el usuario:[" + LdapUserDetailsUtils.getUsuario() + " es parte de todos los grupos"); odes = publi.obtenODESCompartidos(); logger.info("Obtenidos odes de todos los usuarios, numero de odes pendientes de publicacion[" + odes.length); } } catch (Exception ex) { logger.error("Imposible obtener los odes pendientes de publicacion", ex); throw new ValidatorException("{gestorFlujo.error.inesperado}"); } if (odes != null && odes.length > 0) { TransicionConTamainoVO[] odesTamaino = new TransicionConTamainoVO[odes.length]; String[] identificadoresOdesCompartidos = new String[odes.length]; if (logger.isDebugEnabled()) { logger.debug("Entramos en el mapeo de " + odes.length + " elementos"); } for (int i = 0; i < odes.length; i++) { TransicionConTamainoVO conTamaino = new TransicionConTamainoVO(); if (logger.isDebugEnabled()) logger.debug("Estamos en la posicion: " + i); conTamaino.setComentarios(odes[i].getComentarios()); conTamaino.setFecha(odes[i].getFecha()); conTamaino.setIdODE(odes[i].getIdODE()); identificadoresOdesCompartidos[i] = odes[i].getIdODE();//Los guardamos para hacer la consulta al localizador conTamaino.setIdUsuario(odes[i].getIdUsuarioCreacion());//Nombre del creador!!!!!!!!!!!! conTamaino.setTitulo(odes[i].getTitulo()); odesTamaino[i] = conTamaino; } Long[] tamainoOdes = null; if (identificadoresOdesCompartidos != null && identificadoresOdesCompartidos.length > 0) { tamainoOdes = localizador.consultaEspacioLocalizadores(identificadoresOdesCompartidos); } for (int i = 0; i < odes.length; i++) { // Vamos a insertar le tamaino en MB,no en bytes; double mb = (double) tamainoOdes[i] / (1024 * 1024); String pattern = "###.##"; java.text.DecimalFormat myFormatter = new java.text.DecimalFormat(pattern); String output = myFormatter.format(mb); odesTamaino[i].setTamaino(output); if (logger.isDebugEnabled()) logger.debug("Tamaino del ODE compartido con id:" + odesTamaino[i].getIdODE() + ", su div[" + mb + "] y su tamaino es:" + output); } form.setListaODESAsArray(odesTamaino); } else { if (logger.isDebugEnabled()) logger.debug("No tiene objetos compartidos"); form.setListaODESAsArray(odes); } } catch (Exception e) { logger.error("Error al obtener los objetos compartidos: ", e); throw new ValidatorException("{gestor.flujo.error.obtener.compartidos}"); } }
From source file:com.swcguild.springmvcwebapp.controller.Lucky7sController.java
@RequestMapping(value = "/lucky7s", method = RequestMethod.POST) public String doPost(HttpServletRequest request, Model model) { String myAnswer = request.getParameter("myAnswer"); //check if empty, then try catch around conversion to int try {//from w w w .j a v a 2s . c o m int wallet = Integer.parseInt(request.getParameter("myAnswer")); do { int rInt = rGen.nextInt(11) + 2; if (wallet > maxMoney) { maxMoney = wallet; } if (maxMoney <= wallet) { timeToStop = rolls; } wallet = adjustWallet(rInt, wallet); rolls++; } while (wallet >= 1); DecimalFormat df = new DecimalFormat("#.00"); model.addAttribute("rolls", rolls - 1); model.addAttribute("timeToStop", timeToStop); model.addAttribute("maxMoney", df.format(maxMoney)); } catch (NumberFormatException e) { } return "lucky7sResponse"; }
From source file:com.yyl.common.utils.excel.ExcelTools.java
/** * ?excel//from ww w.jav a2 s . co m * @param cell * @return */ private static String getCellValue(Cell cell) { String cellValue = ""; DecimalFormat df = new DecimalFormat("#"); if (cell == null || cell.equals("") || cell.getCellType() == Cell.CELL_TYPE_BLANK) { System.out.println(cellValue); return cellValue; } switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: cellValue = cell.getRichStringCellValue().getString().trim(); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { cellValue = cell.getDateCellValue().toString(); } else { cellValue = df.format(cell.getNumericCellValue()).toString(); } break; case Cell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()).trim(); break; default: cellValue = ""; } return cellValue; }
From source file:com.envision.envservice.service.RankingListService.java
private List<SpiritSortBo> sortuserPraiseNumSort(Map<String, Integer> lowerUserPraiseNum, final SortType sortType) { List<SpiritSortBo> sbos = new ArrayList<SpiritSortBo>(); for (Entry<String, Integer> entry : lowerUserPraiseNum.entrySet()) { if (!TOTAL.equals(entry.getKey())) { SpiritSortBo sbo = new SpiritSortBo(); sbo.setUserId(entry.getKey()); BigDecimal fz = new BigDecimal(entry.getValue()); BigDecimal fm = new BigDecimal(lowerUserPraiseNum.get(TOTAL)); if (fm.intValue() == 0) { sbo.setPercent("0"); } else { DecimalFormat df = new DecimalFormat("0.00"); String pe = df.format(fz.multiply(new BigDecimal(100)).divide(fm, 2, RoundingMode.HALF_UP)); sbo.setPercent(pe);/*from w w w . jav a 2 s.c o m*/ } sbos.add(sbo); } } // ? // Collections.sort(sbos, new SpiritSortBoComparator(sortType)); Collections.sort(sbos, new Comparator<SpiritSortBo>() { public int compare(SpiritSortBo o1, SpiritSortBo o2) { BigDecimal o1Percent = new BigDecimal(o1.getPercent()); BigDecimal o2Percent = new BigDecimal(o2.getPercent()); int multiplier = -1; if (sortType.equals(SortType.ASC)) { multiplier = 1; } return o1Percent.compareTo(o2Percent) * multiplier; } }); return sbos; }
From source file:it.unibas.spicygui.vista.RankedTransformationsTopComponent.java
public Object getValueAt(int rowIndex, int columnIndex) { List<Transformation> rankedTransformations = (List<Transformation>) modello .getBean(Costanti.RANKED_TRANSFORMATIONS); if (rankedTransformations != null) { Transformation transformation = rankedTransformations.get(rowIndex); if (columnIndex == 0) { return NbBundle.getMessage(Costanti.class, Costanti.TRANSFORMATION) + " n." + transformation.getId(); } else if (columnIndex == 1) { SimilarityCheck similarityCheck = (SimilarityCheck) transformation .getAnnotation(SpicyConstants.SIMILARITY_CHECK); double quality = similarityCheck.getQualityMeasure(); DecimalFormat formatter = new DecimalFormat("#.####"); return formatter.format(quality); }/*from w w w . j a va2s.c o m*/ } return null; }
From source file:com.pivotal.gemfire.tools.pulse.internal.service.MemberRegionsService.java
public JSONObject execute(final HttpServletRequest request) throws Exception { // get cluster object Cluster cluster = Repository.get().getCluster(); // json object to be sent as response JSONObject responseJSON = new JSONObject(); try {//from w ww .ja v a 2 s . c om JSONObject requestDataJSON = new JSONObject(request.getParameter("pulseData")); String memberName = requestDataJSON.getJSONObject("MemberRegions").getString("memberName"); Cluster.Member clusterMember = cluster.getMember(StringUtils.makeCompliantName(memberName)); if (clusterMember != null) { responseJSON.put("memberId", clusterMember.getId()); responseJSON.put(this.NAME, clusterMember.getName()); responseJSON.put("host", clusterMember.getHost()); // member's regions Cluster.Region[] memberRegions = clusterMember.getMemberRegionsList(); JSONArray regionsListJson = new JSONArray(); for (Cluster.Region memberRegion : memberRegions) { JSONObject regionJSON = new JSONObject(); regionJSON.put(this.NAME, memberRegion.getName()); if (PulseConstants.PRODUCT_NAME_GEMFIREXD .equalsIgnoreCase(PulseController.getPulseProductSupport())) { // Convert region path to dot separated region path regionJSON.put("fullPath", StringUtils.getTableNameFromRegionName(memberRegion.getFullPath())); } else { regionJSON.put("fullPath", memberRegion.getFullPath()); } regionJSON.put("type", memberRegion.getRegionType()); regionJSON.put("entryCount", memberRegion.getSystemRegionEntryCount()); Long entrySize = memberRegion.getEntrySize(); DecimalFormat form = new DecimalFormat(PulseConstants.DECIMAL_FORMAT_PATTERN_2); String entrySizeInMB = form.format(entrySize / (1024f * 1024f)); if (entrySize < 0) { regionJSON.put(this.ENTRY_SIZE, this.VALUE_NA); } else { regionJSON.put(this.ENTRY_SIZE, entrySizeInMB); } regionJSON.put("scope", memberRegion.getScope()); String diskStoreName = memberRegion.getDiskStoreName(); if (StringUtils.isNotNullNotEmptyNotWhiteSpace(diskStoreName)) { regionJSON.put(this.DISC_STORE_NAME, diskStoreName); regionJSON.put(this.DISC_SYNCHRONOUS, memberRegion.isDiskSynchronous()); } else { regionJSON.put(this.DISC_SYNCHRONOUS, this.VALUE_NA); regionJSON.put(this.DISC_STORE_NAME, ""); } regionJSON.put("gatewayEnabled", memberRegion.getWanEnabled()); regionsListJson.put(regionJSON); } responseJSON.put("memberRegions", regionsListJson); // response responseJSON.put("status", "Normal"); } // Send json response return responseJSON; } catch (JSONException e) { throw new Exception(e); } }
From source file:me.ryandowling.Followers.java
private void moreFollowers() { try {/* w w w . ja v a 2s . co m*/ DecimalFormat formatter = new DecimalFormat("#,###"); FileUtils.write(this.followersTodayTxtFile.toFile(), formatter.format(this.numberOfFollowers - this.startNumberOfFollowers)); FileUtils.write(this.numberOfFollowersFile.toFile(), formatter.format(this.numberOfFollowers)); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.lldp.checksims.algorithm.preprocessor.CommonCodeLineRemovalPreprocessor.java
/** * Perform common code removal using Line Comparison. * * @param removeFrom Submission to remove common code from * @return Input submission with common code removed * @throws InternalAlgorithmError Thrown on error removing common code * @throws InvalidSubmissionException if the submission is in any way invalid *//*from w w w . ja va 2 s.com*/ @Override public Submission process(Submission removeFrom) throws InternalAlgorithmError { logs.debug("Performing common code removal on submission " + removeFrom.getName()); // Use the new submissions to compute this AlgorithmResults results; Tokenizer tokenizer = Tokenizer.getTokenizer(TokenType.LINE); // This exception should never happen, but if it does, just rethrow as InternalAlgorithmException try { results = getResults(removeFrom, common, algorithm).inverse(); } catch (TokenTypeMismatchException e) { throw new InternalAlgorithmError(e.getMessage()); } // The results contains two TokenLists, representing the final state of the submissions after detection // All common code should be marked invalid for the input submission's final list Percentable listWithCommonInvalid; Real percentMatched; if (new ValidityIgnoringSubmission(results.a, tokenizer).equals(removeFrom)) { listWithCommonInvalid = results.getPercentableA(); percentMatched = results.percentMatchedA(); } else if (new ValidityIgnoringSubmission(results.b, tokenizer).equals(removeFrom)) { listWithCommonInvalid = results.getPercentableB(); percentMatched = results.percentMatchedB(); } else { throw new RuntimeException("Unreachable code!"); } // Recreate the string body of the submission from this new list String newBody = listWithCommonInvalid.toString(); DecimalFormat d = new DecimalFormat("###.00"); logs.trace("Submission " + removeFrom.getName() + " contained " + d.format(percentMatched.multiply(new Real(100)).asDouble()) + "% common code"); logs.trace("Removed " + listWithCommonInvalid + " percent of submission"); return new ConcreteSubmission(removeFrom.getName(), newBody); }
From source file:com.cwp.cmoneycharge.activity.AddPayActivity.java
public static double get2Double(String strMoney) { // ?? Double a = Double.parseDouble(strMoney); DecimalFormat df = new DecimalFormat("0.00"); return new Double(df.format(a)); }
From source file:gda.gui.beans.ScannableMotionUnitsBean.java
@Override protected synchronized void refreshValues() { try {/*from w w w. j a v a 2 s . com*/ // get the units unitsString = theScannable.getAttribute(ScannableMotionUnits.USERUNITS).toString(); // generate the tooltip String toolTip = theScannable.getName(); { Double[] limits = (Double[]) theScannable.getAttribute(ScannableMotion.FIRSTINPUTLIMITS); if (limits != null) { toolTip += " (" + ((limits[0] != null) ? limits[0] : "") + ", " + ((limits[1] != null) ? limits[1] : "") + ")"; } } tooltipString = toolTip; // display the current value Double currentPosition = ScannableUtils.getCurrentPositionArray(theScannable)[0]; if (isZeroSmallNumbers() && (math.fabs(currentPosition) < 0.0001)) { DecimalFormat myFormat = new DecimalFormat(); myFormat.applyPattern("#####.####"); String newText = myFormat.format(currentPosition); valueString = newText.trim(); } else { String newText = String.format(getDisplayFormat(), currentPosition); valueString = newText.trim(); } } catch (DeviceException e) { logger.error("Exception while trying to update display " + scannableName + ": " + e.getMessage()); } }