Java Code Examples for java.text.DecimalFormat.format()

The following are Jave code examples for showing how to use format() of the java.text.DecimalFormat class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: poe-ladder-tracker-java   File: LadderCSV.java   View Source Code Vote up 6 votes
/**
 * Returns the experience per hour.
 * 
 * @return The experience per hour as a string.
 */
public String getExpPerHour(){
	if(characterSpecificExpPerHourReferenceLow == 0 || characterSpecificExpPerHourReferenceHigh == 0){
		return "next update";
	}
	else{
		long exp = characterSpecificExpPerHourReferenceHigh-characterSpecificExpPerHourReferenceLow;
		int time = (characterSpecificExpPerHourTimestampHigh-characterSpecificExpPerHourTimestampLow)/1000;
		int expPerHour = (int) (exp/time)*60*60;			
		double tmp;
		DecimalFormat decimalFormat = new DecimalFormat("##0.0");
		
		if(expPerHour < 999){
			tmp = (double) expPerHour;
			return  Integer.toString(expPerHour);
		}
		else if(expPerHour < 999999){
			tmp = (double) expPerHour/1000;
			return decimalFormat.format(tmp) + "K";
		}
		else{
			tmp = (double) expPerHour/1000000;
			return decimalFormat.format(tmp) + "M";
		}
	}
}
 
Example 2
Project: Clipcon-Client   File: ProgressBarScene.java   View Source Code Vote up 6 votes
/** set progress value at progress bar when send file */
public void setProgeress(int index, double value, long onGoing, long fileLength, boolean isDownloading) {
	double onGoingMB = ((onGoing / 1024.0) / 1024.0);
	double fileLengthMB = ((fileLength / 1024.0) / 1024.0);

	DecimalFormat dec = new DecimalFormat("0.0");

	String progress = (int) value + "% (" + dec.format(onGoingMB) + " / " + dec.format(fileLengthMB) + " MB)";

	Platform.runLater(() -> {
		try {
			if(!isDownloading)
				textArray[index].setText("Uploading " + progress);
			else
				textArray[index].setText("Downloading " + progress);

			progressBarArray[index].setProgress(value*0.01);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("index exception");
		}
	});
}
 
Example 3
Project: FacetExtract   File: AAppearedFacet.java   View Source Code Vote up 6 votes
/**
 * 用于把矩阵输出到文件中
 *
 * @param matrix
 * @param outputPath
 */
public static void printMatrix(Matrix matrix, String outputPath) {
    long[] size = matrix.getSize();
    long m = size[0]; long n = size[1];
    String cont = "";
    DecimalFormat df = new DecimalFormat("#0.000000");
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cont = cont + df.format(matrix.getAsDouble(i,j)) + " ";
        }
        cont = cont + "\n";
    }
    try {
        FileUtils.write(new File(outputPath), cont, "utf-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 4
Project: fiery   File: Toolbox.java   View Source Code Vote up 6 votes
public static String printMem(long bytes) {
    double dbytes = (double) bytes;
    DecimalFormat df = new DecimalFormat("#.##");

    if (dbytes < 1024) {
        return df.format(bytes);
    } else if (dbytes < 1024 * 1024) {
        return df.format(dbytes / 1024);
    } else if (dbytes < 1024 * 1024 * 1024) {
        return df.format(dbytes / 1024 / 1024) + "M";
    } else if (dbytes < 1024 * 1024 * 1024 * 1024L) {
        return df.format(dbytes / 1024 / 1024 / 1024) + "G";
    } else {
        return "Too big to show you";
    }
}
 
Example 5
Project: openjdk-jdk10   File: BasisLibrary.java   View Source Code Vote up 6 votes
public static String formatNumber(double number, String pattern,
                                  DecimalFormat formatter) {
    // bugzilla fix 12813
    if (formatter == null) {
        formatter = defaultFormatter;
    }
    try {
        StringBuffer result = threadLocalStringBuffer.get();
    result.setLength(0);
        if (pattern != defaultPattern) {
            formatter.applyLocalizedPattern(pattern);
        }
    formatter.format(number, result, _fieldPosition);
        return result.toString();
    }
    catch (IllegalArgumentException e) {
        runTimeError(FORMAT_NUMBER_ERR, Double.toString(number), pattern);
        return(EMPTYSTRING);
    }
}
 
Example 6
Project: Queue-Manager-Cloud-Dispatcher   File: PersistenceWithSM.java   View Source Code Vote up 5 votes
@Override
  protected void displayTable(HttpServletResponse response) throws SQLException, IOException {
  	response.setIntHeader("Refresh", 5);
  	
  	// Append table that lists all persons
      List<SM> resultList = smDAO.selectAllEntries();
      response.getWriter().println(
              "<p><center><table width=70% border=\"1\"><tr><th colspan=\"1\"></th>" + "<th colspan=\"3\">" + (resultList.isEmpty() ? "" : resultList.size() + " ")
                      + "Employees in the EPM-BPC team</th>"
                      + "<th colspan=\"3\">" + "Smart Sorted</th></tr>");
      if (resultList.isEmpty()) {
          response.getWriter().println("<tr><td colspan=\"4\">Database is empty</td></tr>");
      } else {
          response.getWriter().println("<tr><th>#</th><th>Name</th><th>Assign</th><th>Remove</th><th>Amount</th><th>Total</th><th>AVG Q-DAY</th></tr>");
      }
      IXSSEncoder xssEncoder = XSSEncoder.getInstance();
      int index = 1;
      Collections.sort(resultList); 
   
      // Add [EPM_QM_ASSIGNED] button
  	response.getWriter().println("<p><center> Click here &#8594;  <input type=\"submit\" onclick=\"return window.prompt('Copy to clipboard: ','[EPM_QM_ASSIGNED]')\" value=\"[EPM_QM_ASSIGNED]\"></center></p>");
      
      int smIncidents = 0;
      for (SM sm : resultList) {        	
      	// Graham = 4, Stefan = 12
      	if (sm.getId() == 4 || sm.getId()==12) {
      		// Calculate incident number
      		smIncidents += sm.getSm();
      		
      		// Get score
       	String score = "0";
       	
      		DecimalFormat df = new DecimalFormat("#.###");
      		score = df.format(((double)sm.getSum()) / QueueDays.hash.get(sm.getName()));
      	
       	
       	String pop = sm.getName() + " has been +1, please go for assign.";
       	String link = "<td><center><form action=\"" + LINKNAME + "?Id="+ sm.getId() + "&operation=add\" method=\"post\">" + "<input type=\"submit\" onclick=\"return window.prompt('" + pop + " Copy to clipboard: Ctrl+C, Enter','" + sm.getiNumber() + "')\" value=\"Add\" />" + "</form></center></td>";
       	
       	if (sm.getSum() < FIXEDVALUE) {
       		response.getWriter().println("<tr><td height=\"30\"><center>" + (index++) + "</center></td>");
        	if (index == 2) {
        		response.getWriter().println("<td height=\"30\"><center><mark><b>" + xssEncoder.encodeHTML(sm.getName()+" ("+sm.getiNumber()+")") + "</b></mark></center></td>");
        	} else {
        		response.getWriter().println("<td height=\"30\"><center>" + xssEncoder.encodeHTML(sm.getName()+" ("+sm.getiNumber()+")") + "</center></td>");
        	}
       		response.getWriter().println(link); 
       		response.getWriter().println("<td><center><form action=\"" + LINKNAME + "?Id="+ sm.getId() + "&operation=decrease\" method=\"post\">" + "<input type=\"submit\" value=\"Delete\" />" + "</form></center></td>"); 
        	response.getWriter().println("<td height=\"30\"><center>" + sm.getSm() + "</center></td>");
			response.getWriter().println("<td height=\"30\"><center>" + sm.getSum() + "</center></td>" + "<td height=\"30\"><center>" + score + "</center></td>");
       	} else {
        	response.getWriter().println("<tr><td height=\"30\"><center>" + (index++) + "</center></td>");
        	response.getWriter().println("<td height=\"30\"><center>" + xssEncoder.encodeHTML(sm.getName() + ": UNAVAILABLE") + "</center></td>");
        	response.getWriter().println("<td><center>"+ xssEncoder.encodeHTML("N/A") + "</center></td>"); 
        	response.getWriter().println("<td><center>"+ xssEncoder.encodeHTML("N/A") + "</center></td>"); 
        	response.getWriter().println("<td height=\"30\"><center>" + sm.getSm() + "</center></td>");
			response.getWriter().println("<td height=\"30\"><center>" + (sm.getSum()-FIXEDVALUE) + "</center></td>");
       	}
       	
		response.getWriter().println("</tr>");
      	}
      }
      response.getWriter().println("</table></center></p>");

response.getWriter().println("<p><center>SM has <mark>" + smIncidents + "</mark> incidents" + "</center></p>");
response.getWriter().println("</body>");
      	     
// Home button
response.getWriter().println("<p><center><form action=\"" + "nw" + "\" method=\"get\">" + "<input type=\"submit\" value=\"Return to Home\" />" + "</form></center></p>");
      	
      
  }
 
Example 7
Project: gdl2   File: DvQuantity.java   View Source Code Vote up 5 votes
@Override
public String toString() {
    DecimalFormat format = new DecimalFormat();
    format.setMinimumFractionDigits(precision);
    format.setMaximumFractionDigits(precision);
    DecimalFormatSymbols dfs = format.getDecimalFormatSymbols();
    dfs.setDecimalSeparator(DECIMAL_SEPARATOR);
    format.setDecimalFormatSymbols(dfs);
    format.setGroupingUsed(false);
    return format.format(magnitude) + ((unit == null || unit.isEmpty()) ? "" : "," + getUnit());
}
 
Example 8
Project: datarouter   File: NumberFormatter.java   View Source Code Vote up 5 votes
public static String format(Number number, String prefix, String suffix, int numFractionDigits, boolean grouping){
	DecimalFormat df = new DecimalFormat();
	df.setMaximumFractionDigits(numFractionDigits);
	df.setMinimumFractionDigits(numFractionDigits);
	df.setRoundingMode(RoundingMode.HALF_UP);
	df.setGroupingUsed(grouping);
	df.setPositivePrefix(prefix);
	df.setNegativePrefix(prefix + "-");
	df.setPositiveSuffix(suffix);
	df.setNegativeSuffix(suffix);
	return df.format(number);
}
 
Example 9
Project: easy-sync   File: UploadMonitor.java   View Source Code Vote up 5 votes
private String printPercent() {
    if(uploadedBytes == fileSize || fileSize == 0)
        return "100%";
    else {
        DecimalFormat bd = new DecimalFormat("0.00");
        return bd.format((uploadedBytes) * 100.0 / fileSize) + "%";
    }
}
 
Example 10
Project: COE1186   File: TrainC.java   View Source Code Vote up 5 votes
private String calcPower(double newSpeed) {
	double currSpeed = Double.parseDouble(speedField.getText());
	String strPow;
	double a;
	double Pow;
	DecimalFormat df = new DecimalFormat("#.####");
	if (newSpeed > currSpeed) {
		deactivateService();
               	newSpeed = newSpeed * 0.44704;
		Pow = newSpeed * ((meanAccel * emptyMass) + (emptyMass * mu * g * Math.cos(theta)));
		strPow = df.format(Pow/1000) + "";
		a = .5 * 8052.9706;
		accelField.setText(df.format(a) + "");
	}
	else if (newSpeed == currSpeed) {
		deactivateService();
                newSpeed = newSpeed * 0.44704;
		Pow = newSpeed * emptyMass * Math.cos(theta) * g * mu;
		strPow = df.format(Pow/1000) + "";
		a = 0;
		accelField.setText(df.format(a) + "");
	}
	else {
		strPow = "0";
		activateService();
		a = -(1.2 + (Math.cos(theta) * mu * g));
		a = a *8052.9706;
		accelField.setText(df.format(a) + "");
	}
	return strPow;
}
 
Example 11
Project: AleCulator2   File: CalcMethods.java   View Source Code Vote up 5 votes
public String weightConversion_Grams_To_Ounces(double grams){
	
	DecimalFormat myDF = new DecimalFormat("#.##");
	double ounces;
	String textOunces;
	ounces = (grams/28.34952);
	textOunces = myDF.format(ounces);
	return textOunces;
	
}
 
Example 12
Project: Restaurant   File: ShoppingCart.java   View Source Code Vote up 5 votes
public double calculateTaxes(){
	DecimalFormat df = new DecimalFormat("####0.00");
	
	String tax = df.format(0.0725*this.subTotal);
	this.taxes = Double.parseDouble(tax);
	return this.taxes;
}
 
Example 13
Project: Liteframework   File: FileUtil.java   View Source Code Vote up 5 votes
public static String formatFileSizeToString(long fileLen) {// 转换文件大小
    DecimalFormat df = new DecimalFormat("#.00");
    String fileSizeString = "";
    if (fileLen < 1024) {
        fileSizeString = df.format((double) fileLen) + "B";
    } else if (fileLen < 1048576) {
        fileSizeString = df.format((double) fileLen / 1024) + "K";
    } else if (fileLen < 1073741824) {
        fileSizeString = df.format((double) fileLen / 1048576) + "M";
    } else {
        fileSizeString = df.format((double) fileLen / 1073741824) + "G";
    }
    return fileSizeString;
}
 
Example 14
Project: Queue-Manager-Cloud-Dispatcher   File: PersistenceWithDSM.java   View Source Code Vote up 5 votes
@Override
  protected void displayTable(HttpServletResponse response) throws SQLException, IOException {
      response.setIntHeader("Refresh", 5);
      
  	// Append table that lists all persons
  	List<DSM> resultList = dsmDAO.selectAllEntries();
         	
  	
  	response.getWriter().println(
              "<p><center><table width=70% border=\"1\"><tr><th colspan=\"1\"></th>" + "<th colspan=\"3\">" + (resultList.isEmpty() ? "" : resultList.size() + " ")
                      + "Employees in the EPM-BPC team</th>"
                      + "<th colspan=\"3\">" + "Smart Sorted</th></tr>");
      if (resultList.isEmpty()) {
          response.getWriter().println("<tr><td colspan=\"4\">Database is empty</td></tr>");
      } else {
          response.getWriter().println("<tr><th>#</th><th>Name</th><th>Assign</th><th>Remove</th><th>Amount</th><th>Total</th><th>AVG Q-DAY</th></tr>");
      }
      IXSSEncoder xssEncoder = XSSEncoder.getInstance();
      int index = 1;
      Collections.sort(resultList); 
   
      // Add [qm assign] button
  	response.getWriter().println("<p><center> Click here &#8594;  <input type=\"submit\" onclick=\"return window.prompt('Copy to clipboard: ','[EPM_QM_ASSIGNED]')\" value=\"[EPM_QM_ASSIGNED]\"></center></p>");
      
      int dsmIncidents = 0;
      for (DSM dsm : resultList) {
      	// Graham = 4, Marc = 10
      	if (dsm.getId() == 4 || dsm.getId()==10) {
      		// Calculate incident number
      		dsmIncidents += dsm.getDsm();
      		
       	// Get score
       	String score = "0";
      		DecimalFormat df = new DecimalFormat("#.###");
      		score = df.format(((double)dsm.getSum()) / QueueDays.hash.get(dsm.getName()));
       	
       	String pop = dsm.getName() + " has been +1, please go for assign.";
       	String link = "<td><center><form action=\"" + LINKNAME + "?Id="+ dsm.getId() + "&operation=add\" method=\"post\">" + "<input type=\"submit\" onclick=\"return window.prompt('" + pop + " Copy to clipboard: Ctrl+C, Enter','" + dsm.getiNumber() + "')\" value=\"Add\" />" + "</form></center></td>";
       	
       	if (dsm.getSum() < FIXEDVALUE) {
       		response.getWriter().println("<tr><td height=\"30\"><center>" + (index++) + "</center></td>");
        	if (index == 2) {
        		response.getWriter().println("<td height=\"30\"><center><mark><b>" + xssEncoder.encodeHTML(dsm.getName()+" ("+dsm.getiNumber()+")") + "</b></mark></center></td>");
        	} else {
        		response.getWriter().println("<td height=\"30\"><center>" + xssEncoder.encodeHTML(dsm.getName()+" ("+dsm.getiNumber()+")") + "</center></td>");
        	}
       		response.getWriter().println(link); 
        	response.getWriter().println("<td><center><form action=\"" + LINKNAME + "?Id="+ dsm.getId() + "&operation=decrease\" method=\"post\">" + "<input type=\"submit\" value=\"Delete\" />" + "</form></center></td>"); 
        	response.getWriter().println("<td height=\"30\"><center>" + dsm.getDsm() + "</center></td>");
			response.getWriter().println("<td height=\"30\"><center>" + dsm.getSum() + "</center></td>" + "<td height=\"30\"><center>" + score + "</center></td>");
       	} else {
        	response.getWriter().println("<tr><td height=\"30\"><center>" + (index++) + "</center></td>");
        	response.getWriter().println("<td height=\"30\"><center>" + xssEncoder.encodeHTML(dsm.getName() + ": UNAVAILABLE") + "</center></td>");
        	response.getWriter().println("<td><center>"+ xssEncoder.encodeHTML("N/A") + "</center></td>"); 
        	response.getWriter().println("<td><center>"+ xssEncoder.encodeHTML("N/A") + "</center></td>"); 
        	response.getWriter().println("<td height=\"30\"><center>" + dsm.getDsm() + "</center></td>");
			response.getWriter().println("<td height=\"30\"><center>" + (dsm.getSum()-FIXEDVALUE) + "</center></td>");
		}
       	
		response.getWriter().println("</tr>");
      	}
      }
      
      
response.getWriter().println("</table></center></p>");

response.getWriter().println("<p><center>DSM has <mark>" + dsmIncidents + "</mark> incidents" + "</center></p>");
response.getWriter().println("</body>");
  
// Home button
response.getWriter().println("<p><center><form action=\"" + "nw" + "\" method=\"get\">" + "<input type=\"submit\" value=\"Return to Home\" />" + "</form></center></p>");
      	       
  }
 
Example 15
Project: CXJPadProject   File: ConvertUtils.java   View Source Code Vote up 5 votes
public static String toFileSizeString(long fileSize) {
    DecimalFormat df = new DecimalFormat("0.00");
    String fileSizeString;
    if (fileSize < KB) {
        fileSizeString = fileSize + "B";
    } else if (fileSize < MB) {
        fileSizeString = df.format((double) fileSize / KB) + "K";
    } else if (fileSize < GB) {
        fileSizeString = df.format((double) fileSize / MB) + "M";
    } else {
        fileSizeString = df.format((double) fileSize / GB) + "G";
    }
    return fileSizeString;
}
 
Example 16
Project: oscm   File: VMPropertyHandler.java   View Source Code Vote up 4 votes
public String formatMBasGB(double valueMB) {
    DecimalFormat format = new DecimalFormat("#0.# GB");
    return format
            .format(VMwareValue.fromMegaBytes(valueMB).getValue(Unit.GB));
}
 
Example 17
Project: Clipcon-AndroidClient   File: TransparentActivity.java   View Source Code Vote up 4 votes
public void showUploadProgressNoti() {
    final int id = 1;
    final NotificationManager mNotifyManager =
            (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());

    mBuilder.setContentTitle("Data Upload")
            .setContentText("Upload in progress")
            .setSmallIcon(R.drawable.icon_logo)
            .setProgress(0, 0, true);

    mNotifyManager.notify(id, mBuilder.build());

    RetrofitUploadData.UploadCallback uploadCallback = new RetrofitUploadData.UploadCallback() {
        @Override
        public void onUpload(long onGoing, long fileLength, double progressValue) {
            double onGoingMB = ((onGoing / 1024.0) / 1024.0);
            double fileLengthMB = ((fileLength / 1024.0) / 1024.0);

            DecimalFormat dec = new DecimalFormat("0.0");

            String progress = (int) progressValue + "% (" + dec.format(onGoingMB) + " / " + dec.format(fileLengthMB) + " MB)";

            mBuilder.setProgress(100, (int)progressValue, false);
            mBuilder.setContentText("Uploading...  " + progress);
            mBuilder.setAutoCancel(true);

            mNotifyManager.notify(id, mBuilder.build());
        }
        @Override
        public void onComplete() {
            Intent intent = new Intent(getApplicationContext(), GroupActivity.class);
            intent.putExtra("History", "test");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            mBuilder.setProgress(100, 100, false);
            mBuilder.setContentText("Upload complete");
            mBuilder.setAutoCancel(true);
            mBuilder.setContentIntent(pendingIntent);

            mNotifyManager.notify(id, mBuilder.build());
        }
    };

    Endpoint.getUploader().setUploadCallback(uploadCallback);
}
 
Example 18
Project: Earthquake-report-app   File: EarthquakeAdapter.java   View Source Code Vote up 4 votes
private String formatMagnitude(double magnitude) {
    DecimalFormat magnitudeFormat = new DecimalFormat("0.0");
    return magnitudeFormat.format(magnitude);
}
 
Example 19
Project: cornerstone   File: Tools.java   View Source Code Vote up 4 votes
public final static String naoToSec(long nao){

        DecimalFormat decimalFormat = new DecimalFormat("#,###.### sec");
        return decimalFormat.format(nao/Math.pow(10,9));
    }
 
Example 20
Project: FTC2016   File: Beacon.java   View Source Code Vote up 2 votes
/**
 * Get a confidence string that the beacon analysis is correct
 * <p/>
 * This is an approximation, but can be used carefully to filter out random noise.
 * <p/>
 * Also, only certain analysis methods provide a confidence - this will then return zero.
 *
 * @return Confidence, if applicable - "N/A" if not applicable
 */
public String getConfidenceString() {
    final DecimalFormat format = new DecimalFormat("0.000");
    return !Double.isNaN(confidence) ? format.format(MathUtil.coerce(0, 1, getConfidence()) * 100.0f) + "%" : "N/A";
}