Java Code Examples for java.text.DecimalFormat

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project action-core, under directory /src/main/java/com/ning/metrics/action/hdfs/reader/.

Source file: HdfsEntry.java

  32 
vote

/** 
 * Pretty print the size of the file
 * @return a string representing the size of the file
 */
public String getPrettySize(){
  DecimalFormat format=new DecimalFormat();
  long sizeInBytes=size;
  int i=0;
  while (sizeInBytes > 1023 && i < SIZES.length - 1) {
    sizeInBytes/=1024;
    i+=1;
  }
  if (sizeInBytes < 10) {
    format.setMaximumFractionDigits(1);
  }
  return format.format(sizeInBytes) + " " + SIZES[i];
}
 

Example 2

From project addis, under directory /application/src/main/java/org/drugis/addis/presentation/.

Source file: AbstractForestPlotPresentation.java

  32 
vote

public static List<String> getTickVals(BinnedScale scale,Scale toRender){
  ArrayList<String> tickVals=new ArrayList<String>();
  DecimalFormat df=new DecimalFormat("####.####");
  tickVals.add(df.format(toRender.getMin()));
  tickVals.add(toRender instanceof LogScale ? df.format(1D) : df.format(0D));
  tickVals.add(df.format(toRender.getMax()));
  return tickVals;
}
 

Example 3

From project android-bankdroid, under directory /src/com/liato/bankdroid/.

Source file: Helpers.java

  32 
vote

public static String formatBalance(BigDecimal balance,String curr,boolean round){
  DecimalFormatSymbols dfs=new DecimalFormatSymbols();
  dfs.setDecimalSeparator(',');
  dfs.setGroupingSeparator(' ');
  DecimalFormat currency;
  if (!round) {
    currency=new DecimalFormat("#,##0.00 ");
  }
 else {
    currency=new DecimalFormat("#,##0 ");
  }
  currency.setDecimalFormatSymbols(dfs);
  return currency.format(balance.doubleValue()) + curr;
}
 

Example 4

From project android-joedayz, under directory /Proyectos/AndroidFoursquare/src/com/mycompany/fsq/.

Source file: NearbyAdapter.java

  32 
vote

private String formatDistance(double distance){
  String result="";
  DecimalFormat dF=new DecimalFormat("00");
  dF.applyPattern("0.#");
  if (distance < 1000)   result=dF.format(distance) + " m";
 else {
    distance=distance / 1000.0;
    result=dF.format(distance) + " km";
  }
  return result;
}
 

Example 5

From project Archimedes, under directory /br.org.archimedes.dimension/src/br/org/archimedes/dimension/.

Source file: Dimension.java

  32 
vote

private String getDistanceText() throws NullArgumentException {
  Line lineToMeasure=getDimensionLine();
  Point initial=lineToMeasure.getInitialPoint();
  Point ending=lineToMeasure.getEndingPoint();
  double length=Geometrics.calculateDistance(initial,ending);
  DecimalFormat df=new DecimalFormat();
  String lengthStr=df.format(length);
  return lengthStr;
}
 

Example 6

From project BoneJ, under directory /src/org/doube/jama/.

Source file: Matrix.java

  32 
vote

/** 
 * Print the matrix to the output stream. Line the elements up in columns with a Fortran-like 'Fw.d' style format.
 * @param output Output stream.
 * @param w Column width.
 * @param d Number of digits after the decimal.
 */
public void print(PrintWriter output,int w,int d){
  DecimalFormat format=new DecimalFormat();
  format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
  format.setMinimumIntegerDigits(1);
  format.setMaximumFractionDigits(d);
  format.setMinimumFractionDigits(d);
  format.setGroupingUsed(false);
  print(output,format,w + 2);
}
 

Example 7

From project Bukkit-Plugin-Utilties, under directory /src/main/java/de/xzise/wrappers/economy/.

Source file: EconomyHandler.java

  32 
vote

public static String defaultFormat(double price){
  DecimalFormat fakeForm=new DecimalFormat("#,##0.##");
  String fakeFormed=fakeForm.format(price);
  if (fakeFormed.endsWith(".")) {
    fakeFormed=fakeFormed.substring(0,fakeFormed.length() - 1);
  }
  return fakeFormed;
}
 

Example 8

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/.

Source file: DecimalUtil.java

  32 
vote

/** 
 * Thread-safe version of converting a double value to a String when only a certain number of digits are desired after a decimal point.
 * @param value
 * @param precision
 * @return
 */
public static String toString(double value,int precision){
  StringBuilder buf=new StringBuilder("0");
  if (precision > 0) {
    buf.append(".");
  }
  for (int i=0; i < precision; i++) {
    buf.append("0");
  }
  DecimalFormat format=new DecimalFormat(buf.toString());
  return format.format(value);
}
 

Example 9

From project CloudReports, under directory /src/main/java/cloudreports/gui/datacenters/.

Source file: SpecificDatacenterView.java

  32 
vote

/** 
 * Changes the processing cost of this datacenter whenever the state of the processing cost spinner changes.
 * @param evt     a change event.
 * @since           1.0
 */
private void procCostSpinnerStateChanged(javax.swing.event.ChangeEvent evt){
  DecimalFormat dft=new DecimalFormat("00.###E0");
  String n=String.valueOf(procCostSpinner.getValue());
  getDatacenterRegistry().setCostPerSec(Double.valueOf(n));
  drDAO.updateDatacenterRegistry(getDatacenterRegistry());
  double costPerMips=(getDatacenterRegistry().getCostPerSec() / drDAO.getMips(getDatacenterRegistry().getId()));
  getMipsCostLabel().setText("(Cost per MIPS: " + dft.format(costPerMips) + ")");
}
 

Example 10

From project core_1, under directory /src/com/iCo6/.

Source file: iConomy.java

  32 
vote

/** 
 * Formats the money in a human readable form with the currency attached:<br /><br /> 20000.53 = 20,000.53 Coin<br /> 20000.00 = 20,000 Coin
 * @param amount double
 * @return String
 */
public static String format(double amount){
  DecimalFormat formatter=new DecimalFormat("#,##0.00");
  String formatted=formatter.format(amount);
  if (formatted.endsWith(".")) {
    formatted=formatted.substring(0,formatted.length() - 1);
  }
  return Common.formatted(formatted,Constants.Nodes.Major.getStringList(),Constants.Nodes.Minor.getStringList());
}
 

Example 11

From project cp-common-utils, under directory /src/com/clarkparsia/common/base/.

Source file: Memory.java

  32 
vote

/** 
 * Returns a human-readable representation of bytes similar to how "ls -h" works in Unix systems. The resulting is guaranteed to be 4 characters or less unless the given value is greater than 999TB. The last character in the returned string is one of 'B', 'K', 'M', 'G', or 'T' representing bytes, kilobytes, megabytes, gigabytes or terabytes. This function uses the binary unit system where 1K = 1024B. <p> Examples: <pre> 482 = 482B 1245 = 1.2K 126976 = 124K  4089471 = 3.9M 43316209 =  41M  1987357695 = 1.9G </pre> </p>
 */
public static String readable(long bytes){
  double result=bytes;
  int i=0;
  while (result >= 1000 && i < BYTE_COUNT_SUFFIX.length() - 1) {
    result/=1024.0;
    i++;
  }
  DecimalFormat formatter=(result < 10 && i > 0) ? ONE_FRACTION_DIGIT : NO_FRACTION_DIGIT;
  return formatter.format(result) + BYTE_COUNT_SUFFIX.charAt(i);
}
 

Example 12

From project data-access, under directory /src/org/pentaho/platform/dataaccess/datasource/wizard/models/.

Source file: CsvFileInfo.java

  32 
vote

private List<String> getDummyHeader(int maxColumns){
  List<String> dummy=new ArrayList<String>(maxColumns);
  DecimalFormat df=new DecimalFormat("000");
  for (int i=0; i < maxColumns; i++) {
    dummy.add(DEFAULT_COLUMN_NAME_PREFIX + df.format(i + 1));
  }
  return dummy;
}
 

Example 13

From project dawn-common, under directory /org.dawb.common.ui/src/org/dawb/common/ui/views/monitor/.

Source file: MonitorPreferencePage.java

  32 
vote

@Override protected void checkState(){
  super.checkState();
  try {
    DecimalFormat format=new DecimalFormat(formatFieldEditor.getStringValue());
    format.format(100.001);
  }
 catch (  IllegalArgumentException ne) {
    setErrorMessage("The format '" + formatFieldEditor.getStringValue() + "' is not valid.");
    setValid(false);
    return;
  }
  setErrorMessage(null);
  setValid(true);
}
 

Example 14

From project dawn-ui, under directory /org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/tools/fitting/.

Source file: FittedPeak.java

  32 
vote

public String getTabString(){
  DecimalFormat format=new DecimalFormat("##0.#####E0");
  final StringBuilder buf=new StringBuilder();
  buf.append(format.format(getPosition()));
  buf.append("\t");
  buf.append(format.format(getFWHM()));
  buf.append("\t");
  buf.append(format.format(getArea()));
  return buf.toString();
}
 

Example 15

From project drools-planner, under directory /drools-planner-benchmark/src/main/java/org/drools/planner/benchmark/core/measurement/.

Source file: ScoreDifferencePercentage.java

  32 
vote

public String toString(Locale locale){
  StringBuilder s=new StringBuilder(percentageLevels.length * 8);
  DecimalFormat decimalFormat=new DecimalFormat("0.00%",DecimalFormatSymbols.getInstance(locale));
  for (int i=0; i < percentageLevels.length; i++) {
    if (i > 0) {
      s.append("/");
    }
    s.append(decimalFormat.format(percentageLevels[i]));
  }
  return s.toString();
}
 

Example 16

From project fauxclock, under directory /src/com/teamkang/fauxclock/factories/.

Source file: CpuFactory.java

  32 
vote

public static String formatVolts(int mV){
  int s;
  double n=mV / 1000.0;
  DecimalFormat dF=new DecimalFormat("###.###");
  String formatted=dF.format(n);
  if (n > 0)   formatted="+" + formatted;
  return formatted + " mV";
}
 

Example 17

From project fedora-client, under directory /fedora-client-core/src/main/java/com/yourmediashelf/fedora/util/.

Source file: DateUtility.java

  32 
vote

public static DateTimeFormatter getXSDFormatter(DateTime date){
  int len=0;
  int millis=date.getMillisOfSecond();
  if (millis > 0) {
    DecimalFormat df=new DecimalFormat(".###");
    double d=millis / 1000.0;
    len=String.valueOf(df.format(d)).length() - 1;
  }
  return getXSDFormatter(len);
}
 

Example 18

From project FScape, under directory /src/main/java/de/sciss/fscape/gui/.

Source file: BeltramiDecompositionDlg.java

  32 
vote

protected void printVector(float[] v,String name){
  final DecimalFormat fmt=getDecimalFormat();
  System.out.println("Vector '" + name + "':");
  System.out.print("   ");
  for (int j=0; j < v.length; j++) {
    System.out.print("          [," + j + "]");
  }
  System.out.println();
  System.out.print(" [1]");
  for (int j=0; j < v.length; j++) {
    System.out.print(" " + fmt.format(v[j]));
  }
  System.out.println("\n");
}
 

Example 19

From project GnucashMobile, under directory /GnucashMobile/src/org/gnucash/android/ui/transactions/.

Source file: NewTransactionFragment.java

  32 
vote

@Override public void afterTextChanged(Editable s){
  if (s.length() == 0)   return;
  BigDecimal amount=parseInputToDecimal(s.toString());
  DecimalFormat formatter=(DecimalFormat)NumberFormat.getInstance(Locale.getDefault());
  formatter.setMinimumFractionDigits(2);
  formatter.setMaximumFractionDigits(2);
  current=formatter.format(amount.doubleValue());
  mAmountEditText.removeTextChangedListener(this);
  mAmountEditText.setText(current);
  mAmountEditText.setSelection(current.length());
  mAmountEditText.addTextChangedListener(this);
}
 

Example 20

From project gpslogger, under directory /GPSLogger/src/com/mendhak/gpslogger/common/.

Source file: OpenGTSClient.java

  32 
vote

/** 
 * Encode a location as GPRMC string data. <p/> For details check org.opengts.util.Nmea0183#_parse_GPRMC(String) (OpenGTS source)
 * @param loc location
 * @return GPRMC data
 */
public static String GPRMCEncode(Location loc){
  DecimalFormatSymbols dfs=new DecimalFormatSymbols(Locale.US);
  DecimalFormat f=new DecimalFormat("0.000000",dfs);
  String gprmc=String.format("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,,","$GPRMC",NMEAGPRMCTime(new Date(loc.getTime())),"A",NMEAGPRMCCoord(Math.abs(loc.getLatitude())),(loc.getLatitude() >= 0) ? "N" : "S",NMEAGPRMCCoord(Math.abs(loc.getLongitude())),(loc.getLongitude() >= 0) ? "E" : "W",f.format(MetersPerSecondToKnots(loc.getSpeed())),f.format(loc.getBearing()),NMEAGPRMCDate(new Date(loc.getTime())));
  gprmc+="*" + NMEACheckSum(gprmc);
  return gprmc;
}
 

Example 21

From project gxa, under directory /atlas-utils/src/main/java/uk/ac/ebi/gxa/utils/.

Source file: NumberFormatUtil.java

  32 
vote

String formatNumber(double number){
  DecimalFormat df=new DecimalFormat(E_PATTERN);
  String auxFormat=df.format(number);
  String[] formatParts=auxFormat.split(E);
  String mantissa=formatParts[0];
  int exponent=Integer.parseInt(formatParts[1]);
  if (exponent >= -3 && exponent <= 0) {
    return new DecimalFormat("#.###").format(number);
  }
  return new StringBuilder().append(mantissa).append(MULTIPLY_HTML_CODE).append(TEN).append(SUP_PRE).append(exponent).append(SUP_POST).toString();
}
 

Example 22

From project Hphoto, under directory /src/java/com/hphoto/util/.

Source file: StringUtil.java

  32 
vote

/** 
 * Format a percentage for presentation to the user.
 * @param done the percentage to format (0.0 to 1.0)
 * @param digits the number of digits past the decimal point
 * @return a string representation of the percentage
 */
public static String formatPercent(double done,int digits){
  DecimalFormat percentFormat=new DecimalFormat("0.0%");
  double scale=Math.pow(10.0,digits + 2);
  double rounded=Math.floor(done * scale);
  percentFormat.setDecimalSeparatorAlwaysShown(false);
  percentFormat.setMinimumFractionDigits(digits);
  percentFormat.setMaximumFractionDigits(digits);
  return percentFormat.format(rounded / scale);
}
 

Example 23

From project iciql, under directory /src/com/iciql/util/.

Source file: IciqlLogger.java

  32 
vote

private static void logStat(StatementType type,long value){
  if (value > 0) {
    DecimalFormat df=new DecimalFormat("###,###,###,###");
    logStatement(StatementType.STAT,StringUtils.pad(type.name(),6," ",true) + " = " + df.format(value));
  }
}
 

Example 24

From project imageflow, under directory /src/de/danielsenff/imageflow/models/parameter/.

Source file: ParameterWidgetFactory.java

  32 
vote

public void parameterChanged(Parameter source){
  if (source.getValue() instanceof String) {
    component.setText((String)source.getValue());
  }
 else   if (source.getValue() instanceof Integer) {
    component.setText(Integer.toString((Integer)source.getValue()));
  }
 else   if (source.getValue() instanceof Double) {
    Double value=(Double)source.getValue();
    DecimalFormat decimal=new DecimalFormat("0.00");
    decimal.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    component.setText(decimal.format(value));
  }
}
 

Example 25

From project incubator-cordova-android, under directory /framework/src/org/apache/cordova/.

Source file: Globalization.java

  32 
vote

private JSONObject getNumberToString(JSONArray options) throws GlobalizationError {
  JSONObject obj=new JSONObject();
  String value="";
  try {
    DecimalFormat fmt=getNumberFormatInstance(options);
    value=fmt.format(options.getJSONObject(0).get(NUMBER));
    return obj.put("value",value);
  }
 catch (  Exception ge) {
    throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR);
  }
}
 

Example 26

From project incubator-deltaspike, under directory /deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/config/injectable/numberconfig/.

Source file: NumberConfigPropertyProducer.java

  32 
vote

@Produces @Dependent @NumberConfig(name="unused") public Float produceNumberProperty(InjectionPoint injectionPoint) throws ParseException {
  NumberConfig metaData=getAnnotation(injectionPoint,NumberConfig.class);
  String configuredValue=getPropertyValue(metaData.name(),metaData.defaultValue());
  if (configuredValue == null) {
    return null;
  }
  DecimalFormat df=new DecimalFormat(metaData.pattern(),new DecimalFormatSymbols(Locale.US));
  return df.parse(configuredValue).floatValue();
}
 

Example 27

From project Java3DTest, under directory /Java3D/src/.

Source file: Logger.java

  32 
vote

public String getDateAndTime(){
  String output="";
  DecimalFormat fmt=new DecimalFormat("00");
  Calendar now=Calendar.getInstance();
  int yyyy=now.get(Calendar.YEAR);
  int mm=now.get(Calendar.MONTH) + 1;
  int dd=now.get(Calendar.DAY_OF_MONTH);
  int h=now.get(Calendar.HOUR_OF_DAY);
  int m=now.get(Calendar.MINUTE);
  int s=now.get(Calendar.SECOND);
  output=String.format("%s_%s_%s_%s_%s_%s",yyyy,fmt.format(mm),fmt.format(dd),fmt.format(h),fmt.format(m),fmt.format(s));
  return output;
}
 

Example 28

From project jDTO-Binder, under directory /jdto/src/main/java/org/jdto/mergers/.

Source file: DecimalFormatMerger.java

  32 
vote

/** 
 * Merge a number by using a  {@link DecimalFormat} instance.
 * @param value the number to be formatted.
 * @param extraParam the format string.
 * @return the merged object formatted with JDK decimal format.
 */
@Override public String mergeObjects(Number value,String[] extraParam){
  if (value == null) {
    return null;
  }
  DecimalFormat format=getDecimalFormat(extraParam);
  return format.format(value);
}
 

Example 29

From project jentrata-msh, under directory /Plugins/CorvusEbMS/src/test/java/hk/hku/cecid/ebms/spa/.

Source file: EbmsUtilityTest.java

  32 
vote

/** 
 * Get the local timezone represenetation from the UTC. The returned  format is "GMT+hh:mm". <br/><br/> For example, if you are located in Asia/Hong Kong, the returned string should be "GMT+08:00".   
 */
public String getLocalTimezone(){
  TimeZone tz=TimeZone.getDefault();
  int tzOffset=tz.getOffset(new Date().getTime());
  DecimalFormat twoDigits=new DecimalFormat("00");
  String sign="+";
  if (tzOffset < 0) {
    sign="-";
    tzOffset=-tzOffset;
  }
  int hours=(tzOffset / 3600000);
  int minutes=(tzOffset % 3600000) / 60000;
  return new StringBuffer("GMT").append(sign).append(twoDigits.format(hours)).append(":").append(twoDigits.format(minutes)).toString();
}
 

Example 30

From project JoSQL, under directory /src/main/java/com/gentlyweb/utils/.

Source file: StringUtils.java

  32 
vote

/** 
 * Convert a string to a set of character entities.  
 * @param str The string to convert.
 * @return The converted string.
 */
public static String convertStringToCharEntities(String str){
  DecimalFormat df=new DecimalFormat("000");
  StringBuffer buf=new StringBuffer();
  char chars[]=str.toCharArray();
  for (int i=0; i < chars.length; i++) {
    buf.append("&#");
    buf.append(df.format((int)chars[i]));
    buf.append(';');
  }
  return buf.toString();
}
 

Example 31

From project LTE-Simulator, under directory /src/rs/etf/igor/.

Source file: UI.java

  32 
vote

private void printReuse(){
  double helper=3 * ((double)(deltaSlider.getValue() * alphaSlider.getValue()) + (double)(100 - deltaSlider.getValue()) * (double)(2 * gammaSlider.getValue() + betaSlider.getValue()) / 3) / 10000;
  DecimalFormat num;
  if (helper >= 10.0) {
    num=new DecimalFormat("##.###");
  }
 else {
    num=new DecimalFormat("#.###");
  }
  String string=num.format(helper);
  string=string.replace(',','.');
  helper=Double.valueOf(string);
  reuseLabel.setText("Reuse ratio: " + helper + "/3");
}
 

Example 32

From project maven-wagon, under directory /wagon-providers/wagon-scm/src/main/java/org/apache/maven/wagon/providers/scm/.

Source file: ScmWagon.java

  32 
vote

private File createCheckoutDirectory(){
  File checkoutDirectory;
  DecimalFormat fmt=new DecimalFormat("#####");
  Random rand=new Random(System.currentTimeMillis() + Runtime.getRuntime().freeMemory());
synchronized (rand) {
    do {
      checkoutDirectory=new File(System.getProperty("java.io.tmpdir"),"wagon-scm" + fmt.format(Math.abs(rand.nextInt())) + ".checkout");
    }
 while (checkoutDirectory.exists());
  }
  return checkoutDirectory;
}
 

Example 33

From project MEditor, under directory /editor-converter/src/main/java/cz/mzk/editor/server/convert/.

Source file: Converter.java

  32 
vote

public static void main(String... args){
  Converter convertor=Converter.getInstance();
  String inputPrefix="/home/meditor/input/monograph/test/";
  String outputPrefix="/home/meditor/imageserver/unknown/test/";
  DecimalFormat nf=new DecimalFormat("0000");
  for (int i=1; i <= 10; i++) {
    String input=inputPrefix + nf.format(i) + ".jpg";
    String output=outputPrefix + i + ".jp2";
    convertor.convert(input,output);
  }
}
 

Example 34

From project medsavant, under directory /MedSavantShared/src/org/ut/biolab/medsavant/util/.

Source file: MiscUtils.java

  32 
vote

public static String numToString(double num,int significantdigits){
  String formatString="###,###";
  if (significantdigits > 0) {
    formatString+=".";
    for (int i=0; i < significantdigits; i++) {
      formatString+="#";
    }
  }
  DecimalFormat df=new DecimalFormat(formatString);
  return df.format(num);
}
 

Example 35

From project Memcached-Java-Load-Client, under directory /src/com/yahoo/ycsb/measurements/.

Source file: OneMeasurementTimeSeries.java

  32 
vote

@Override public String getSummary(){
  if (windowoperations == 0) {
    return "";
  }
  DecimalFormat d=new DecimalFormat("#.##");
  double report=((double)windowtotallatency) / ((double)windowoperations);
  windowtotallatency=0;
  windowoperations=0;
  return "[" + getName() + " AverageLatency(ms)="+ d.format(report)+ "]";
}
 

Example 36

From project mes, under directory /mes-plugins/mes-plugins-minimal-affordable-quantity/src/main/java/com/qcadoo/mes/minimalAffordableQuantity/.

Source file: QuantityService.java

  32 
vote

private BigDecimal getBigDecimalFromField(final Object value,final Locale locale){
  try {
    DecimalFormat format=(DecimalFormat)DecimalFormat.getInstance(locale);
    format.setParseBigDecimal(true);
    return new BigDecimal(format.parse(value.toString()).doubleValue());
  }
 catch (  ParseException e) {
    throw new IllegalStateException(e.getMessage(),e);
  }
}
 

Example 37

From project metric, under directory /src/main/java/com/gnapse/metric/.

Source file: NumberFormatter.java

  32 
vote

private DecimalFormat createPlainFormat(){
  final DecimalFormatSymbols symbols=DecimalFormatSymbols.getInstance(this.locale);
  symbols.setGroupingSeparator(DEFAULT_GROUP_SEPARATOR);
  final DecimalFormat format=(DecimalFormat)NumberFormat.getNumberInstance(this.locale);
  format.setDecimalFormatSymbols(symbols);
  format.setMaximumFractionDigits(MAX_FRACTION_DIGITS);
  return format;
}
 

Example 38

From project netnumeri, under directory /src/com/netnumeri/shared/finance/utils/.

Source file: FormatUtils.java

  32 
vote

public static String format(double d,Locale locale){
  DecimalFormat format=(DecimalFormat)NumberFormat.getNumberInstance(locale);
  format.applyPattern("###,###.###");
  format.setMinimumIntegerDigits(1);
  format.setMaximumFractionDigits(2);
  format.setMinimumFractionDigits(2);
  format.setGroupingUsed(false);
  return format.format(d);
}
 

Example 39

From project aether-ant, under directory /src/main/java/org/eclipse/aether/ant/listeners/.

Source file: AntTransferListener.java

  31 
vote

@Override public void transferSucceeded(TransferEvent event){
  String msg=event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded";
  msg+=" " + event.getResource().getRepositoryUrl() + event.getResource().getResourceName();
  long contentLength=event.getTransferredBytes();
  if (contentLength >= 0) {
    String len=contentLength >= 1024 ? ((contentLength + 1023) / 1024) + " KB" : contentLength + " B";
    String throughput="";
    long duration=System.currentTimeMillis() - event.getResource().getTransferStartTime();
    if (duration > 0) {
      DecimalFormat format=new DecimalFormat("0.0",new DecimalFormatSymbols(Locale.ENGLISH));
      double kbPerSec=(contentLength / 1024.0) / (duration / 1000.0);
      throughput=" at " + format.format(kbPerSec) + " KB/sec";
    }
    msg+=" (" + len + throughput+ ")";
  }
  task.log(msg);
}
 

Example 40

From project aether-demo, under directory /aether-demo-snippets/src/main/java/org/eclipse/aether/examples/util/.

Source file: ConsoleTransferListener.java

  31 
vote

@Override public void transferSucceeded(TransferEvent event){
  transferCompleted(event);
  TransferResource resource=event.getResource();
  long contentLength=event.getTransferredBytes();
  if (contentLength >= 0) {
    String type=(event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
    String len=contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";
    String throughput="";
    long duration=System.currentTimeMillis() - resource.getTransferStartTime();
    if (duration > 0) {
      DecimalFormat format=new DecimalFormat("0.0",new DecimalFormatSymbols(Locale.ENGLISH));
      double kbPerSec=(contentLength / 1024.0) / (duration / 1000.0);
      throughput=" at " + format.format(kbPerSec) + " KB/sec";
    }
    out.println(type + ": " + resource.getRepositoryUrl()+ resource.getResourceName()+ " ("+ len+ throughput+ ")");
  }
}
 

Example 41

From project android-client_2, under directory /src/org/mifos/androidclient/entities/account/.

Source file: RepaymentScheduleItem.java

  31 
vote

@Override public String getListLabel(){
  double feeAmount=0;
  DecimalFormat df=new DecimalFormat("#.##");
  double feePaid=0;
  double total=0;
  for (int i=0; i < feesActionDetails.size(); i++) {
    feeAmount+=feesActionDetails.get(i).getFeeAmount();
    feePaid+=feesActionDetails.get(i).getFeeAmountPaid();
  }
  if (paymentStatus == 1) {
    total=feePaid + miscFeePaid + principalPaid+ interestPaid;
  }
 else   total=(feeAmount - feePaid) + (miscFee - miscFeePaid) + (principal - principalPaid)+ (interest - interestPaid);
  if (paymentDate != null && paymentStatus == 1) {
    return DateUtils.format(dueDate) + "   " + DateUtils.format(paymentDate)+ "     "+ Double.valueOf(df.format(round(total)));
  }
 else   if (paymentDate != null && paymentStatus != 1) {
    return DateUtils.format(dueDate) + "  Partially paid     " + Double.valueOf(df.format(round(total)));
  }
 else   return DateUtils.format(dueDate) + "   Not paid yet     " + Double.valueOf(df.format(round(total)));
}
 

Example 42

From project AndroidCommon, under directory /src/com/asksven/android/common/kernelutils/.

Source file: State.java

  31 
vote

/** 
 * Formats a freq in Hz in a readable form
 * @param freqHz
 * @return
 */
String formatFreq(int freqkHz){
  double freq=freqkHz;
  double freqMHz=freq / 1000;
  double freqGHz=freq / 1000 / 1000;
  String formatedFreq="";
  DecimalFormat df=new DecimalFormat("#.##");
  if (freqGHz >= 1) {
    formatedFreq=df.format(freqGHz) + " GHz";
  }
 else   if (freqMHz >= 1) {
    formatedFreq=df.format(freqMHz) + " MHz";
  }
 else {
    formatedFreq=df.format(freqkHz) + " kHz";
  }
  return formatedFreq;
}
 

Example 43

From project ant4eclipse, under directory /org.ant4eclipse.lib.pydt.test/src-framework/org/ant4eclipse/testframework/.

Source file: ProjectSuite.java

  31 
vote

/** 
 * Initialises this project suite
 * @param wsbuilder The builder used for the workspace. Not <code>null</code>.
 * @param dltk <code>true</code> <=> Use a DLTK based python nature, PyDev otherwise.
 */
public ProjectSuite(WorkspaceBuilder wsbuilder,boolean dltk){
  Assert.assertNotNull(wsbuilder);
  this._workspacebuilder=wsbuilder;
  this._dltk=dltk;
  this._count=1;
  this._formatter=new DecimalFormat("000");
  this._sampleegg=getResource("/org/ant4eclipse/testframework/sample.egg");
  this._samplejar=getResource("/org/ant4eclipse/testframework/sample.jar");
  this._samplezip=getResource("/org/ant4eclipse/testframework/sample.zip");
}
 

Example 44

From project babel, under directory /src/main/lexinduct/.

Source file: DataPreparer.java

  31 
vote

protected void dictCoverage(Dictionary dict,Set<EquivalenceClass> eqs,boolean src){
  DecimalFormat df=new DecimalFormat("0.00");
  double tokTotal=0;
  double tokCovered=0;
  double typCovered=0;
  Number numProp;
  double num;
  for (  EquivalenceClass eq : eqs) {
    if (null != (numProp=((Number)eq.getProperty(Number.class.getName())))) {
      num=numProp.getNumber();
      if ((src && dict.containsSrc(eq)) || (!src && dict.containsTrg(eq))) {
        tokCovered+=num;
        typCovered++;
      }
      tokTotal+=num;
    }
  }
  LOG.info("[" + dict.getName() + (src ? "]: source" : "]: target")+ " dictionary coverage "+ df.format(100.0 * tokCovered / tokTotal)+ "% tokens and "+ df.format(100.0 * typCovered / (double)eqs.size())+ "% types.");
}
 

Example 45

From project bioclipse.speclipse, under directory /plugins/net.bioclipse.spectrum/src/net/bioclipse/spectrum/editor/.

Source file: PeakLabelProvider.java

  31 
vote

public String getColumnText(Object element,int columnIndex){
  String result="";
  CMLPeak peak=(CMLPeak)element;
  DecimalFormat df=new DecimalFormat("#.00");
switch (columnIndex) {
case 0:
    result=df.format(peak.getXValue());
  break;
case 1:
if (Double.isNaN(peak.getYValue())) result=new String("0");
 else result=df.format(peak.getYValue());
break;
case 2:
if (peak.getAttribute(peakTableViewer.getCmlPeakFields()[0]) != null) result=peak.getAttribute(peakTableViewer.getCmlPeakFields()[0]).getValue();
break;
case 3:
if (peak.getAttribute(peakTableViewer.getCmlPeakFields()[1]) != null) result=peak.getAttribute(peakTableViewer.getCmlPeakFields()[1]).getValue();
break;
case 4:
if (peak.getAttribute(peakTableViewer.getCmlPeakFields()[2]) != null) result=peak.getAttribute(peakTableViewer.getCmlPeakFields()[2]).getValue();
break;
case 5:
if (peak.getAttribute(peakTableViewer.getCmlPeakFields()[3]) != null) result=peak.getAttribute(peakTableViewer.getCmlPeakFields()[3]).getValue();
break;
default :
break;
}
return result;
}
 

Example 46

From project blog_1, under directory /stat4j/src/net/sourceforge/stat4j/filter/.

Source file: RegExpScraper.java

  31 
vote

public Double scrapUserDefinedValue(String text,String pattern){
  if ((text == null) || (text.length() == 0) || (pattern == null)|| (pattern.length() == 0)) {
    return null;
  }
  Pattern p=getPattern(pattern);
  Matcher m=p.matcher(text);
  try {
    if (!m.matches())     return null;
    String str=m.group(1);
    DecimalFormat df=(DecimalFormat)format.get();
    Number value=df.parse(str);
    return new Double(value.doubleValue());
  }
 catch (  Exception ex) {
    return null;
  }
}
 

Example 47

From project cb2java, under directory /src/main/java/net/sf/cb2java/types/.

Source file: Numeric.java

  31 
vote

public DecimalFormat getFormatObject(){
  StringBuffer buffer=new StringBuffer("#");
  for (int i=0; i < digits(); i++) {
    if (i + decimalPlaces() == digits()) {
      buffer.append('.');
    }
    buffer.append('0');
  }
  if (decimalPlaces() < 1)   buffer.append('.');
  buffer.append('#');
  return new DecimalFormat(buffer.toString());
}
 

Example 48

From project ChessCraft, under directory /src/main/java/me/desht/chesscraft/util/.

Source file: ChessUtils.java

  31 
vote

public static String formatStakeStr(double stake){
  try {
    if (ChessCraft.economy != null && ChessCraft.economy.isEnabled()) {
      return ChessCraft.economy.format(stake);
    }
  }
 catch (  Exception e) {
    LogUtils.warning("Caught exception from " + ChessCraft.economy.getName() + " while trying to format quantity "+ stake+ ":");
    e.printStackTrace();
    LogUtils.warning("ChessCraft will continue but you should verify your economy plugin configuration.");
  }
  return new DecimalFormat("#0.00").format(stake);
}
 

Example 49

From project cipango, under directory /cipango-console/src/main/java/org/cipango/console/.

Source file: SipManager.java

  31 
vote

public Table getAppSessionStats() throws Exception {
  ObjectName[] contexts=PrinterUtil.getSipAppContexts(_mbsc);
  Table table=new Table(_mbsc,contexts,"sip.applicationSessions");
  for (  Header header : table.getHeaders()) {
    int index=header.getName().indexOf("Sip application sessions");
    if (index != -1)     header.setName(header.getName().substring(0,index));
  }
  for (  Row row : table) {
    for (    Value value : row.getValues()) {
      if (value.getValue() instanceof Double) {
        DecimalFormat format=new DecimalFormat();
        format.setMaximumFractionDigits(2);
        value.setValue(format.format(value.getValue()));
      }
    }
  }
  return table;
}
 

Example 50

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/.

Source file: NumberUtilities.java

  31 
vote

public static String convertToDecimalNotation(String numberAsString){
  if (numberAsString.indexOf("E") != -1 || numberAsString.indexOf("e") != -1) {
    Format format=new DecimalFormat(UNROUNDED_DECIMAL_PATTERN);
    try {
      return format.format(new Double(numberAsString));
    }
 catch (    NumberFormatException numberFormatException) {
      return NOT_A_NUMBER_PREFIX + " (" + numberAsString+ ")";
    }
  }
  return numberAsString;
}
 

Example 51

From project Clotho-Core, under directory /ClothoApps/SequenceChecker/src/jaligner/.

Source file: Alignment.java

  31 
vote

/** 
 * Returns a summary for alignment
 * @return {@link String} alignment summary
 */
public String getSummary(){
  StringBuffer buffer=new StringBuffer();
  DecimalFormat f1=new DecimalFormat("0.00");
  DecimalFormat f2=new DecimalFormat("0.00%");
  int length=getSequence1().length;
  buffer.append("Sequence #1: " + getName1());
  buffer.append(Commons.getLineSeparator());
  buffer.append("Sequence #2: " + getName2());
  buffer.append(Commons.getLineSeparator());
  buffer.append("Length #1: " + getOriginalSequence1().length());
  buffer.append(Commons.getLineSeparator());
  buffer.append("Length #2: " + getOriginalSequence2().length());
  buffer.append(Commons.getLineSeparator());
  buffer.append("Matrix: " + (matrix.getId() == null ? "" : matrix.getId()));
  buffer.append(Commons.getLineSeparator());
  buffer.append("Gap open: " + open);
  buffer.append(Commons.getLineSeparator());
  buffer.append("Gap extend: " + extend);
  buffer.append(Commons.getLineSeparator());
  buffer.append("Length: " + length);
  buffer.append(Commons.getLineSeparator());
  buffer.append("Identity: " + identity + "/"+ length+ " ("+ f2.format(identity / (float)length)+ ")");
  buffer.append(Commons.getLineSeparator());
  buffer.append("Similarity: " + similarity + "/"+ length+ " ("+ f2.format(similarity / (float)length)+ ")");
  buffer.append(Commons.getLineSeparator());
  buffer.append("Gaps: " + gaps + "/"+ length+ " ("+ f2.format(gaps / (float)length)+ ")");
  buffer.append(Commons.getLineSeparator());
  buffer.append("Score: " + f1.format(score));
  buffer.append(Commons.getLineSeparator());
  return buffer.toString();
}
 

Example 52

From project Cloud9, under directory /src/dist/edu/umd/cloud9/collection/clue/.

Source file: ClueWarcForwardIndex.java

  31 
vote

@Override public ClueWarcRecord getDocument(int docno){
  long start=System.currentTimeMillis();
  if (docno < getFirstDocno() || docno > getLastDocno())   return null;
  int idx=Arrays.binarySearch(docnos,docno);
  if (idx < 0) {
    idx=-idx - 2;
  }
  DecimalFormat df=new DecimalFormat("00000");
  String file=collectionPath + "/part-" + df.format(fileno[idx]);
  LOG.info("fetching docno " + docno + ": seeking to "+ offsets[idx]+ " at "+ file);
  try {
    SequenceFile.Reader reader=new SequenceFile.Reader(fs,new Path(file),conf);
    IntWritable key=new IntWritable();
    ClueWarcRecord value=new ClueWarcRecord();
    reader.seek(offsets[idx]);
    while (reader.next(key)) {
      if (key.get() == docno) {
        break;
      }
    }
    reader.getCurrentValue(value);
    reader.close();
    long duration=System.currentTimeMillis() - start;
    LOG.info(" docno " + docno + " fetched in "+ duration+ "ms");
    return value;
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 53

From project codjo-broadcast, under directory /codjo-broadcast-common/src/main/java/net/codjo/broadcast/common/columns/.

Source file: NumberColumnGenerator.java

  31 
vote

/** 
 * Initialisation du separateur de decimales pour le format de sortie.
 * @param decimalSeparator Le separateur de decimales a utiliser
 * @param decimalPattern   Description of the Parameter
 */
private void initFormat(String decimalSeparator,String decimalPattern){
  if (".".equals(decimalSeparator)) {
    formatFloatOUT=new DecimalFormat(decimalPattern,new DecimalFormatSymbols(Locale.ENGLISH));
  }
 else   if (",".equals(decimalSeparator)) {
    formatFloatOUT=new java.text.DecimalFormat(decimalPattern,new DecimalFormatSymbols(Locale.FRENCH));
  }
 else {
    throw new IllegalArgumentException("Separateur de d?imal non support : " + decimalSeparator);
  }
}
 

Example 54

From project codjo-imports, under directory /codjo-imports-plugin/codjo-imports-plugin-filter/codjo-imports-plugin-filter-kernel/src/main/java/net/codjo/imports/plugin/filter/kernel/.

Source file: DefaultImportFunctionHolder.java

  31 
vote

public BigDecimal stringToDecimal(String value,String format){
  DecimalFormat df=(DecimalFormat)DecimalFormat.getNumberInstance(Locale.US);
  if (format != null) {
    df.applyPattern(format);
  }
  BigDecimal result;
  try {
    String stringValue=df.parse(value).toString();
    result=new BigDecimal(stringValue);
  }
 catch (  ParseException e) {
    result=new BigDecimal(0);
  }
  return result;
}
 

Example 55

From project codjo-standalone-common, under directory /src/main/java/net/codjo/gui/renderer/.

Source file: NumberFormatRenderer.java

  31 
vote

private void initNumberFormat(){
  NUMBER_FORMAT_2DEC=new DecimalFormat("#####0.00",new DecimalFormatSymbols(locale));
  NUMBER_FORMAT_5DEC=new DecimalFormat("#####0.00000",new DecimalFormatSymbols(locale));
  NUMBER_FORMAT_6DEC=new DecimalFormat("#####0.000000",new DecimalFormatSymbols(Locale.FRANCE));
  NUMBER_FORMAT_8DEC=new DecimalFormat("#####0.00000000",new DecimalFormatSymbols(Locale.FRANCE));
  NUMBER_FORMAT_15DEC=new DecimalFormat("#####0.000000000000000",new DecimalFormatSymbols(Locale.FRANCE));
  NUMBER_FORMAT_DEFAULT=NumberFormat.getNumberInstance(Locale.FRANCE);
}
 

Example 56

From project egit-github, under directory /org.eclipse.mylyn.github.core/src/org/eclipse/mylyn/internal/github/core/gist/.

Source file: GistTaskDataHandler.java

  31 
vote

private String formatSize(long size){
  if (size == 1)   return Messages.GistTaskDataHandler_SizeByte;
 else   if (size < 1024)   return new DecimalFormat(Messages.GistTaskDataHandler_SizeBytes).format(size);
 else   if (size >= 1024 && size <= 1048575)   return new DecimalFormat(Messages.GistTaskDataHandler_SizeKilobytes).format(size / 1024.0);
 else   if (size >= 1048576 && size <= 1073741823)   return new DecimalFormat(Messages.GistTaskDataHandler_SizeMegabytes).format(size / 1048576.0);
 else   return new DecimalFormat(Messages.GistTaskDataHandler_SizeGigabytes).format(size / 1073741824.0);
}
 

Example 57

From project en, under directory /src/l1j/server/server/model/.

Source file: L1PcInventory.java

  31 
vote

public int calcWeight240(int weight){
  int weight240=0;
  if (Config.RATE_WEIGHT_LIMIT != 0) {
    double maxWeight=_owner.getMaxWeight();
    if (weight > maxWeight) {
      weight240=240;
    }
 else {
      double wpTemp=(weight * 100 / maxWeight) * 240.00 / 100.00;
      DecimalFormat df=new DecimalFormat("00.##");
      df.format(wpTemp);
      wpTemp=Math.round(wpTemp);
      weight240=(int)(wpTemp);
    }
  }
 else {
    weight240=0;
  }
  return weight240;
}
 

Example 58

From project encog-java-examples, under directory /src/main/java/org/encog/examples/neural/predict/market/.

Source file: MarketEvaluate.java

  31 
vote

public static void evaluate(File dataDir){
  File file=new File(dataDir,Config.NETWORK_FILE);
  if (!file.exists()) {
    System.out.println("Can't read file: " + file.getAbsolutePath());
    return;
  }
  BasicNetwork network=(BasicNetwork)EncogDirectoryPersistence.loadObject(file);
  MarketMLDataSet data=grabData();
  DecimalFormat format=new DecimalFormat("#0.0000");
  int count=0;
  int correct=0;
  for (  MLDataPair pair : data) {
    MLData input=pair.getInput();
    MLData actualData=pair.getIdeal();
    MLData predictData=network.compute(input);
    double actual=actualData.getData(0);
    double predict=predictData.getData(0);
    double diff=Math.abs(predict - actual);
    Direction actualDirection=determineDirection(actual);
    Direction predictDirection=determineDirection(predict);
    if (actualDirection == predictDirection)     correct++;
    count++;
    System.out.println("Day " + count + ":actual="+ format.format(actual)+ "("+ actualDirection+ ")"+ ",predict="+ format.format(predict)+ "("+ predictDirection+ ")"+ ",diff="+ diff);
  }
  double percent=(double)correct / (double)count;
  System.out.println("Direction correct:" + correct + "/"+ count);
  System.out.println("Directional Accuracy:" + format.format(percent * 100) + "%");
}
 

Example 59

From project eoit, under directory /EOIT/src/fr/eoit/activity/fragment/iteminfo/.

Source file: PricesDialog.java

  31 
vote

@Override protected void onCreateSimpleDialog(View inflatedLayout,Bundle savedInstanceState){
  if (savedInstanceState != null) {
    itemId=savedInstanceState.getInt("itemId");
    chosenPriceId=savedInstanceState.getInt("chosenPriceId");
    fixedPrice=savedInstanceState.getDouble("fixedPrice");
  }
  nfPercent=new DecimalFormat("##0.#%");
  this.inflatedLayout=inflatedLayout;
}
 

Example 60

From project fanfoudroid, under directory /src/com/ch_linghu/fanfoudroid/util/.

Source file: DebugTimer.java

  31 
vote

public DebugProfile(String tag,long inc,double incPercent){
  this.tag=tag;
  this.inc=inc;
  percent=new DecimalFormat("0.00#%");
  this.incPercent=percent.format(incPercent);
}
 

Example 61

From project figgo, under directory /src/main/java/br/octahedron/figgo/.

Source file: FiggoI18nResponseInterceptor.java

  31 
vote

private static NumberFormat createNumberFormat(Locale lc){
  DecimalFormatSymbols symbols=new DecimalFormatSymbols(lc);
  symbols.setDecimalSeparator(',');
  symbols.setGroupingSeparator('.');
  return new DecimalFormat("#,##0.00",symbols);
}
 

Example 62

From project GeoBI, under directory /print/src/main/java/org/mapfish/print/map/readers/google/.

Source file: GoogleMapReader.java

  31 
vote

protected void renderTiles(TileRenderer formatter,Transformer transformer,URI commonUri,ParallelMapTileLoader parallelMapTileLoader) throws IOException, URISyntaxException {
  float maxGeoX=transformer.getRotatedMaxGeoX();
  float minGeoX=transformer.getRotatedMinGeoX();
  float maxGeoY=transformer.getRotatedMaxGeoY();
  float minGeoY=transformer.getRotatedMinGeoY();
  long width=transformer.getRotatedBitmapW();
  long height=transformer.getRotatedBitmapH();
  float targetResolution=transformer.getGeoW() / width;
  GoogleLayerInfo.ResolutionInfo resolution=layerInfo.getNearestResolution(targetResolution);
  Map<String,List<String>> tileParams=new HashMap<String,List<String>>();
  double latitude;
  double longitude;
  double originShift=20037508.342789244;
  longitude=(((maxGeoX + minGeoX) / 2.0) / originShift) * 180.0;
  latitude=(((maxGeoY + minGeoY) / 2.0) / originShift) * 180.0;
  latitude=180 / Math.PI * (2 * Math.atan(Math.exp(latitude * Math.PI / 180.0)) - Math.PI / 2.0);
  DecimalFormat df=new DecimalFormat("#.#######################");
  String center=df.format(latitude) + "," + df.format(longitude);
  String size=Long.toString(width) + "x" + Long.toString(height);
  URIUtils.addParamOverride(tileParams,"center",center);
  URIUtils.addParamOverride(tileParams,"size",size);
  URIUtils.addParamOverride(tileParams,"zoom",Integer.toString(resolution.index));
  URI uri=URIUtils.addParams(commonUri,tileParams,OVERRIDE_ALL);
  List<URI> uris=new ArrayList<URI>(1);
  uris.add(config.signURI(uri));
  formatter.render(transformer,uris,parallelMapTileLoader,context,opacity,1,0,0,transformer.getRotatedBitmapW(),transformer.getRotatedBitmapH());
}
 

Example 63

From project gitblit, under directory /src/com/gitblit/utils/.

Source file: ByteFormat.java

  31 
vote

public StringBuffer format(Object obj,StringBuffer buf,FieldPosition pos){
  if (obj instanceof Number) {
    long numBytes=((Number)obj).longValue();
    if (numBytes < 1024) {
      DecimalFormat formatter=new DecimalFormat("#,##0");
      buf.append(formatter.format((double)numBytes)).append(" b");
    }
 else     if (numBytes < 1024 * 1024) {
      DecimalFormat formatter=new DecimalFormat("#,##0");
      buf.append(formatter.format((double)numBytes / 1024.0)).append(" KB");
    }
 else     if (numBytes < 1024 * 1024 * 1024) {
      DecimalFormat formatter=new DecimalFormat("#,##0.0");
      buf.append(formatter.format((double)numBytes / (1024.0 * 1024.0))).append(" MB");
    }
 else {
      DecimalFormat formatter=new DecimalFormat("#,##0.0");
      buf.append(formatter.format((double)numBytes / (1024.0 * 1024.0 * 1024.0))).append(" GB");
    }
  }
  return buf;
}
 

Example 64

From project heritrix3, under directory /engine/src/main/java/org/archive/crawler/util/.

Source file: LogReader.java

  31 
vote

/** 
 * @param fileName
 * @return
 * @throws IOException
 */
private static CompositeFileReader seriesReader(String fileName) throws IOException {
  LinkedList<File> filenames=new LinkedList<File>();
  int seriesNumber=1;
  NumberFormat fmt=new DecimalFormat("00000");
  String predecessorFilename=fileName + fmt.format(seriesNumber);
  while ((new File(predecessorFilename)).exists()) {
    filenames.add(new File(predecessorFilename));
    seriesNumber++;
    predecessorFilename=fileName + fmt.format(seriesNumber);
  }
  filenames.add(new File(fileName));
  return new CompositeFileReader(filenames);
}
 

Example 65

From project hive-udf, under directory /src/main/java/com/nexr/platform/hive/udf/.

Source file: GenericUDFToNumber.java

  31 
vote

@Override public Object evaluate(DeferredObject[] arguments) throws HiveException {
  if (arguments[0].get() == null) {
    return null;
  }
  try {
    Text value=(Text)converters[0].convert(arguments[0].get());
    Locale locale=Locale.getDefault();
    NumberFormat formatter=NumberFormat.getInstance(locale);
    if (formatter instanceof DecimalFormat) {
      DecimalFormat df=(DecimalFormat)formatter;
      if (returnInspector.getTypeName() == Constants.BIGINT_TYPE_NAME) {
        longResult.set(df.parse(value.toString()).longValue());
        return longResult;
      }
      String pattern=((Text)converters[1].convert(arguments[1].get())).toString();
      pattern=pattern.replace("9","0");
      df.applyPattern(pattern);
      doubleResult.set(df.parse(value.toString()).doubleValue());
    }
    return doubleResult;
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 66

From project Holo-Edit, under directory /holoedit/data/.

Source file: HoloTraj.java

  31 
vote

public String toICSTFile(){
  DecimalFormat formateur=(DecimalFormat)NumberFormat.getInstance();
  DecimalFormatSymbols symboles=new DecimalFormatSymbols();
  symboles.setDecimalSeparator('.');
  formateur.setDecimalFormatSymbols(symboles);
  formateur.setMinimumIntegerDigits(1);
  formateur.setMinimumFractionDigits(1);
  formateur.setMaximumFractionDigits(8);
  StringBuffer res=new StringBuffer("\n<ambiscore version=\"1.0\">\n");
  res.append("\t<xyz-def handedness=\"right\" x-axis=\"right\" />\n");
  res.append("\t<trajectory>\n");
  int cpt=0;
  for (  HoloPoint hp : points) {
    res.append("\t\t<point>\n");
    res.append("\t\t\t<time>" + (hp.date) + "</time>\n");
    res.append("\t\t\t<xyz>" + formateur.format((hp.x) / 100) + " "+ formateur.format((hp.y) / 100)+ " "+ formateur.format((hp.z) / 100)+ "</xyz>\n");
    res.append("\t\t\t<editable>" + (hp.isEditable() ? "true" : "false") + "</editable>\n");
    res.append("\t\t</point>\n");
    cpt++;
  }
  res.append("\t</trajectory>\n");
  res.append("</ambiscore>\n");
  return res.toString();
}
 

Example 67

From project ISAcreator, under directory /src/main/java/org/isatools/isacreator/spreadsheet/.

Source file: Utils.java

  31 
vote

/** 
 * Converts a double value to contain decimal places in the frequency the original value was recorded.
 * @param originalVal  - e.g. "2.34"
 * @param valToProcess e.g. 2.999987895
 * @return - 3.00 in the case of the example above as a Double
 */
public static Double formatDoubleValue(String originalVal,Double valToProcess){
  StringBuffer format=new StringBuffer("#");
  int numDecimals;
  int numKeyVals=originalVal.length();
  if (originalVal.contains(".")) {
    format.append(".");
    numDecimals=originalVal.substring(originalVal.lastIndexOf(".") + 1).trim().length();
    for (int i=0; i < numDecimals; i++) {
      format.append("#");
    }
    numKeyVals=originalVal.substring(0,originalVal.lastIndexOf(".")).trim().length();
  }
  for (int i=0; i < numKeyVals; i++) {
    format.insert(0,"#");
  }
  DecimalFormat df=new DecimalFormat(format.toString());
  return Double.valueOf(df.format(valToProcess));
}
 

Example 68

From project JavaFastPFOR, under directory /src/integercompression/.

Source file: BenchmarkBitPacking.java

  31 
vote

public static void test(boolean verbose){
  DecimalFormat dfspeed=new DecimalFormat("0");
  final int N=32;
  final int times=100000;
  Random r=new Random(0);
  int[] data=new int[N];
  int[] compressed=new int[N];
  int[] uncompressed=new int[N];
  for (int bit=0; bit < 31; ++bit) {
    long comp=0;
    long decomp=0;
    for (int t=0; t < times; ++t) {
      for (int k=0; k < N; ++k) {
        data[k]=r.nextInt(1 << bit);
      }
      long time1=System.nanoTime();
      BitPacking.fastpack(data,0,compressed,0,bit);
      long time2=System.nanoTime();
      BitPacking.fastunpack(compressed,0,uncompressed,0,bit);
      long time3=System.nanoTime();
      comp+=time2 - time1;
      decomp+=time3 - time2;
    }
    if (verbose)     System.out.println("bit = " + bit + " comp. speed = "+ dfspeed.format(N * times * 1000.0 / (comp))+ " decomp. speed = "+ dfspeed.format(N * times * 1000.0 / (decomp)));
  }
}
 

Example 69

From project jboss-jsf-api_spec, under directory /src/main/java/javax/faces/convert/.

Source file: NumberConverter.java

  31 
vote

/** 
 * <p/> Override the formatting locale's default currency symbol with the specified currency code (specified via the "currencyCode" attribute) or currency symbol (specified via the "currencySymbol" attribute).</p> <p/> <p>If both "currencyCode" and "currencySymbol" are present, "currencyCode" takes precedence over "currencySymbol" if the java.util.Currency class is defined in the container's runtime (that is, if the container's runtime is J2SE 1.4 or greater), and "currencySymbol" takes precendence over "currencyCode" otherwise.</p> <p/> <p>If only "currencyCode" is given, it is used as a currency symbol if java.util.Currency is not defined.</p> <pre> Example: <p/> JDK    "currencyCode" "currencySymbol" Currency symbol being displayed ----------------------------------------------------------------------- all         ---            ---         Locale's default currency symbol <p/> <1.4        EUR            ---         EUR >=1.4       EUR            ---         Locale's currency symbol for Euro <p/> all         ---           \u20AC       \u20AC <p/> <1.4        EUR           \u20AC       \u20AC >=1.4       EUR           \u20AC       Locale's currency symbol for Euro </pre>
 * @param formatter The <code>NumberFormatter</code> to be configured
 */
private void configureCurrency(NumberFormat formatter) throws Exception {
  String code=null;
  String symbol=null;
  if ((currencyCode == null) && (currencySymbol == null)) {
    return;
  }
  if ((currencyCode != null) && (currencySymbol != null)) {
    if (currencyClass != null)     code=currencyCode;
 else     symbol=currencySymbol;
  }
 else   if (currencyCode == null) {
    symbol=currencySymbol;
  }
 else {
    if (currencyClass != null)     code=currencyCode;
 else     symbol=currencyCode;
  }
  if (code != null) {
    Object[] methodArgs=new Object[1];
    Method m=currencyClass.getMethod("getInstance",GET_INSTANCE_PARAM_TYPES);
    methodArgs[0]=code;
    Object currency=m.invoke(null,methodArgs);
    Class[] paramTypes=new Class[1];
    paramTypes[0]=currencyClass;
    Class numberFormatClass=Class.forName("java.text.NumberFormat");
    m=numberFormatClass.getMethod("setCurrency",paramTypes);
    methodArgs[0]=currency;
    m.invoke(formatter,methodArgs);
  }
 else {
    DecimalFormat df=(DecimalFormat)formatter;
    DecimalFormatSymbols dfs=df.getDecimalFormatSymbols();
    dfs.setCurrencySymbol(symbol);
    df.setDecimalFormatSymbols(dfs);
  }
}
 

Example 70

From project jboss-jstl-api_spec, under directory /src/main/java/org/apache/taglibs/standard/tag/common/fmt/.

Source file: FormatNumberSupport.java

  31 
vote

private void setCurrency(NumberFormat formatter) throws Exception {
  String code=null;
  String symbol=null;
  if ((currencyCode == null) && (currencySymbol == null)) {
    return;
  }
  if ((currencyCode != null) && (currencySymbol != null)) {
    if (currencyClass != null)     code=currencyCode;
 else     symbol=currencySymbol;
  }
 else   if (currencyCode == null) {
    symbol=currencySymbol;
  }
 else {
    if (currencyClass != null)     code=currencyCode;
 else     symbol=currencyCode;
  }
  if (code != null) {
    Object[] methodArgs=new Object[1];
    Method m=currencyClass.getMethod("getInstance",GET_INSTANCE_PARAM_TYPES);
    methodArgs[0]=code;
    Object currency=m.invoke(null,methodArgs);
    Class[] paramTypes=new Class[1];
    paramTypes[0]=currencyClass;
    Class numberFormatClass=Class.forName("java.text.NumberFormat");
    m=numberFormatClass.getMethod("setCurrency",paramTypes);
    methodArgs[0]=currency;
    m.invoke(formatter,methodArgs);
  }
 else {
    DecimalFormat df=(DecimalFormat)formatter;
    DecimalFormatSymbols dfs=df.getDecimalFormatSymbols();
    dfs.setCurrencySymbol(symbol);
    df.setDecimalFormatSymbols(dfs);
  }
}
 

Example 71

From project jclouds-examples, under directory /cloudwatch-basics/src/main/java/org/jclouds/examples/cloudwatch/basics/.

Source file: MainApp.java

  31 
vote

public static void main(String[] args){
  if (args.length < PARAMETERS) {
    throw new IllegalArgumentException(INVALID_SYNTAX);
  }
  String accessKeyId=args[0];
  String secretKey=args[1];
  ComputeServiceContext awsEC2Context=null;
  RestContext<CloudWatchClient,CloudWatchAsyncClient> cloudWatchContext=null;
  try {
    cloudWatchContext=ContextBuilder.newBuilder(new AWSCloudWatchProviderMetadata()).credentials(accessKeyId,secretKey).build();
    awsEC2Context=ContextBuilder.newBuilder(new AWSEC2ProviderMetadata()).credentials(accessKeyId,secretKey).build(ComputeServiceContext.class);
    Set<? extends ComputeMetadata> allNodes=awsEC2Context.getComputeService().listNodes();
    for (    ComputeMetadata node : allNodes) {
      String nodeId=node.getProviderId();
      String region=getRegion(node.getLocation());
      MetricClient metricClient=cloudWatchContext.getApi().getMetricClientForRegion(region);
      int metricsCount=getMetricsCountForInstance(cloudWatchContext.getApi(),region,nodeId);
      double[] cpuUtilization=getCPUUtilizationStatsForInstanceOverTheLast24Hours(metricClient,nodeId);
      String cpuUtilizationHeader="  CPU utilization statistics: ";
      DecimalFormat df=new DecimalFormat("#.##");
      System.out.println(nodeId + " CloudWatch Metrics (Past 24 hours)");
      System.out.println("  Total metrics stored: " + metricsCount);
      if (cpuUtilization == null) {
        System.out.println(cpuUtilizationHeader + "Unable to compute as there are no CPU utilization " + "metrics stored.");
      }
 else {
        System.out.println(cpuUtilizationHeader + df.format(cpuUtilization[0]) + "% (avg), "+ df.format(cpuUtilization[1])+ "% (max), "+ df.format(cpuUtilization[2])+ "% (min)");
      }
    }
  }
  finally {
    if (awsEC2Context != null) {
      awsEC2Context.close();
    }
    if (cloudWatchContext != null) {
      cloudWatchContext.close();
    }
  }
}
 

Example 72

From project JGlobus, under directory /gridftp/src/main/java/org/globus/ftp/.

Source file: GridFTPClient.java

  31 
vote

/** 
 * Change the modification time of a file.
 * @param year      Modifcation year
 * @param month     Modification month (1-12)
 * @param day       Modification day (1-31)
 * @param hour      Modification hour (0-23)
 * @param min       Modification minutes (0-59)
 * @param sec       Modification seconds (0-59)
 * @param file      file whose modification time should be changed
 * @throws IOException
 * @throws ServerException if an error occurred.
 */
public void changeModificationTime(int year,int month,int day,int hour,int min,int sec,String file) throws IOException, ServerException {
  DecimalFormat df2=new DecimalFormat("00");
  DecimalFormat df4=new DecimalFormat("0000");
  String arguments=df4.format(year) + df2.format(month) + df2.format(day)+ df2.format(hour)+ df2.format(min)+ df2.format(sec)+ " "+ file;
  Command cmd=new Command("SITE UTIME",arguments);
  try {
    controlChannel.execute(cmd);
  }
 catch (  UnexpectedReplyCodeException urce) {
    throw ServerException.embedUnexpectedReplyCodeException(urce);
  }
catch (  FTPReplyParseException rpe) {
    throw ServerException.embedFTPReplyParseException(rpe);
  }
}
 

Example 73

From project jMemorize, under directory /src/jmemorize/gui/swing/panels/.

Source file: HistoryChartPanel.java

  31 
vote

private void setupRenderer(CategoryPlot plot){
  DecimalFormat format=new DecimalFormat("####");
  format.setNegativePrefix("");
  StackedBarRenderer renderer=new StackedBarRenderer();
  renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}",format));
  renderer.setItemLabelsVisible(true);
  renderer.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,TextAnchor.HALF_ASCENT_CENTER));
  renderer.setSeriesPaint(0,ColorConstants.EXPIRED_CARDS);
  renderer.setSeriesPaint(1,ColorConstants.RELEARNED_CARDS);
  renderer.setSeriesPaint(2,ColorConstants.LEARNED_CARDS);
  renderer.setMaximumBarWidth(0.2);
  CategoryItemRenderer renderer2=new LineAndShapeRenderer(true,false);
  renderer2.setSeriesPaint(0,new Color(75,150,200));
  plot.setRenderer(1,renderer2);
  plot.setRenderer(renderer);
}
 

Example 74

From project Jobs, under directory /src/main/java/me/zford/jobs/bukkit/.

Source file: JobsCommands.java

  31 
vote

/** 
 * Displays info about a particular action
 * @param player - the player of the job
 * @param prog - the job we are displaying info about
 * @param type - the type of action
 * @return the message
 */
private String jobInfoMessage(JobsPlayer player,Job job,ActionType type){
  StringBuilder message=new StringBuilder();
  message.append(plugin.getMessageConfig().getMessage(type.getName().toLowerCase() + "-header")).append("\n");
  DecimalFormat format=new DecimalFormat("#.##");
  int level=1;
  JobProgression prog=player.getJobProgression(job);
  if (prog != null)   level=prog.getLevel();
  int numjobs=player.getJobProgression().size();
  List<JobInfo> jobInfo=job.getJobInfo(type);
  for (  JobInfo info : jobInfo) {
    String myMessage;
    if (info.getName().contains(":")) {
      myMessage=plugin.getMessageConfig().getMessage(type.getName().toLowerCase() + "-info-sub");
      myMessage=myMessage.replace("%item%",info.getName().split(":")[0].replace("_"," ").toLowerCase());
      myMessage=myMessage.replace("%subitem%",info.getName().split(":")[1]);
    }
 else {
      myMessage=plugin.getMessageConfig().getMessage(type.getName().toLowerCase() + "-info-no-sub");
      myMessage=myMessage.replace("%item%",info.getName().replace("_"," ").toLowerCase());
    }
    myMessage=myMessage.replace("%income%",format.format(info.getIncome(level,numjobs)));
    myMessage=myMessage.replace("%experience%",format.format(info.getExperience(level,numjobs)));
    message.append(myMessage).append("\n");
  }
  return message.toString();
}
 

Example 75

From project joshua, under directory /src/joshua/metrics/.

Source file: GradeLevelBLEU.java

  31 
vote

public void printDetailedScore_fromStats(int[] stats,boolean oneLiner){
  DecimalFormat df=new DecimalFormat("#.###");
  double source_gl=gradeLevel(stats[tokenLength(SOURCE)],stats[syllableLength(SOURCE)],stats[sentCountIndex]);
  double cand_gl=gradeLevel(stats[tokenLength(CANDIDATE)],stats[syllableLength(CANDIDATE)],stats[sentCountIndex]);
  double ref_gl=gradeLevel(stats[tokenLength(REFERENCE)],stats[syllableLength(REFERENCE)],stats[sentCountIndex]);
  double penalty=1;
  double bleu_ref=super.score(stats);
  double bleu_src=srcBLEU.score(stats);
  double bleu_plus=BLEU_plus(bleu_ref,bleu_src);
  if (useTarget)   penalty=getReadabilityPenalty(cand_gl,targetGL);
 else   penalty=getReadabilityPenalty(cand_gl,source_gl);
  if (oneLiner) {
    System.out.print("GL_BLEU=" + df.format(score(stats)));
    System.out.print(" BLEU=" + df.format(bleu_ref));
    System.out.print(" BLEU_src=" + df.format(bleu_src));
    System.out.print(" iBLEU=" + df.format(bleu_plus));
    System.out.print(" GL_cand=" + df.format(cand_gl));
    System.out.print(" GL_src=" + df.format(source_gl));
    System.out.print(" GL_ref=" + df.format(ref_gl));
    System.out.print(" Read_penalty=" + df.format(penalty));
    System.out.println();
  }
 else {
    System.out.println("GL_BLEU      = " + df.format(score(stats)));
    System.out.println("BLEU         = " + df.format(bleu_ref));
    System.out.println("BLEU_src     = " + df.format(bleu_src));
    System.out.println("iBLEU        = " + df.format(bleu_plus));
    System.out.println("GL_cand      = " + df.format(cand_gl));
    System.out.println("GL_src       = " + df.format(source_gl));
    System.out.println("GL_ref       = " + df.format(ref_gl));
    System.out.println("Read penalty = " + df.format(penalty));
  }
}
 

Example 76

From project jPOS, under directory /jpos/src/main/java/org/jpos/iso/.

Source file: IFA_LLABINARY.java

  31 
vote

/** 
 * @param c - a component
 * @return packed component
 * @exception ISOException
 */
public byte[] pack(ISOComponent c) throws ISOException {
  int len;
  byte[] b=(byte[])c.getValue();
  if ((len=b.length) > getLength() || len > 99)   throw new ISOException("invalid len " + len + " packing field "+ (Integer)c.getKey());
  byte[] data=ISOUtil.hexString((byte[])c.getValue()).getBytes();
  byte[] nb=new byte[2 + data.length];
  byte[] length=new DecimalFormat("00").format(len).getBytes();
  System.arraycopy(length,0,nb,0,2);
  System.arraycopy(data,0,nb,2,data.length);
  return nb;
}
 

Example 77

From project lesscss4j, under directory /src/main/java/org/localmatters/lesscss4j/model/expression/.

Source file: ConstantColor.java

  31 
vote

@Override public String toString(){
  if (getAlpha() != null) {
    DecimalFormat alphaFormat=new DecimalFormat("0.###");
    return "rgba(" + getRed() + ','+ getGreen()+ ','+ getBlue()+ ','+ alphaFormat.format(getAlpha())+ ')';
  }
  String rs=Integer.toHexString(getRed());
  String gs=Integer.toHexString(getGreen());
  String bs=Integer.toHexString(getBlue());
  int r=getRed();
  int g=getGreen();
  int b=getBlue();
  if (((r & 0xf0) >> 4) == (r & 0xf) && ((g & 0xf0) >> 4) == (g & 0xf) && ((b & 0xf0) >> 4) == (b & 0xf)) {
    return "#" + rs.charAt(0) + gs.charAt(0)+ bs.charAt(0);
  }
 else {
    StringBuilder buf=new StringBuilder("#");
    appendColorStr(buf,rs);
    appendColorStr(buf,gs);
    appendColorStr(buf,bs);
    return buf.toString();
  }
}
 

Example 78

From project lilith, under directory /benchmark/src/main/java/de/huxhorn/lilith/benchmark/.

Source file: Benchmark.java

  31 
vote

private void logBenchmark(String name,String action,long size,int amount,long expiredNanos){
  double fraction=(double)expiredNanos / 1000000000;
  double eventsFraction=((double)amount) / fraction;
  if (logger.isDebugEnabled())   logger.debug("{}: expired={}s",name,fraction);
  if (logger.isDebugEnabled())   logger.debug("{}: events/s={}",name,eventsFraction);
  if (logger.isDebugEnabled())   logger.debug("{}: size={} bytes",name,size);
  long eventAverage=size / amount;
  String formattedAverage=HumanReadable.getHumanReadableSize(eventAverage,true,false) + "bytes";
  String formattedLength=HumanReadable.getHumanReadableSize(size,true,false) + "bytes";
  DecimalFormatSymbols symbols=new DecimalFormatSymbols();
  symbols.setGroupingSeparator(',');
  symbols.setDecimalSeparator('.');
  DecimalFormat format=new DecimalFormat("#,##0.0#",symbols);
  String formattedEvents=format.format(eventsFraction);
  String formattedFraction=format.format(fraction);
  if (logger.isDebugEnabled())   logger.debug("average={}/event",name,formattedAverage);
  if (logger.isInfoEnabled()) {
    logger.info("|| {} || {} || {} || {} || {} || {} ({}) || {} ||",new Object[]{name,action,amount,formattedFraction,formattedEvents,formattedLength,size,formattedAverage});
  }
}
 

Example 79

From project liquidfeedback-java-sdk, under directory /examples/src/main/java/lfapi/v2/services/example/.

Source file: SampleSchulzeMethodGraphs.java

  31 
vote

/** 
 * To dot.
 * @param dir the dir
 * @param name the name
 * @param vc the vc
 * @param d the d
 * @param p the p
 * @param strongPath the strong path
 * @param K the k
 * @param overlap the overlap
 * @param radius the radius
 * @param edgePos the edge pos
 * @throws Exception the exception
 */
public static void toDot(String dir,String name,ArrayList<VoteCandidate> vc,int[][] d,int[][] p,Path strongPath,double K,boolean overlap,double radius,Map<String,String> edgePos) throws Exception {
  SchulzeMethodNode[] smn=new SchulzeMethodNode[p.length];
  DecimalFormat f=new DecimalFormat("#0.00");
  for (int i=0; i < vc.size(); i++) {
    double ang=((double)(i - 0.5) / vc.size()) * Math.PI * 2.0;
    double x=Math.sin(ang) * radius * 2.0 + radius;
    double y=Math.cos(ang) * radius * 2.0 + radius;
    String pos=f.format(x) + "," + f.format(y)+ "!";
    boolean selected=false;
    if (strongPath != null && strongPath.contains(i)) {
      selected=true;
    }
    smn[i]=new SchulzeMethodNode(vc.get(i).id,pos,selected);
  }
  SchulzeMethodEdge[] sme=new SchulzeMethodEdge[p.length * (p.length - 1) / 2];
  int idx=0;
  for (int i=0; i < d.length; i++) {
    for (int j=0; j < i; j++) {
      boolean selected=false;
      if (strongPath != null && strongPath.contains(i,j)) {
        selected=true;
      }
      String ep=null;
      if (d[i][j] > d[j][i]) {
        if (edgePos != null && edgePos.containsKey(vc.get(i).id + vc.get(j).id)) {
          ep=edgePos.get(vc.get(i).id + vc.get(j).id);
        }
        sme[idx++]=new SchulzeMethodEdge(vc.get(i).id,vc.get(j).id,d[i][j],selected,ep);
      }
 else {
        if (edgePos != null && edgePos.containsKey(vc.get(j).id + vc.get(i).id)) {
          ep=edgePos.get(vc.get(j).id + vc.get(i).id);
        }
        sme[idx++]=new SchulzeMethodEdge(vc.get(j).id,vc.get(i).id,d[j][i],selected,ep);
      }
    }
  }
  toDot(name,dir + name.replaceAll(" ","_"),smn,sme,K,overlap);
}
 

Example 80

From project mapfish-print, under directory /src/main/java/org/mapfish/print/map/readers/google/.

Source file: GoogleMapReader.java

  31 
vote

protected void renderTiles(TileRenderer formatter,Transformer transformer,URI commonUri,ParallelMapTileLoader parallelMapTileLoader) throws IOException, URISyntaxException {
  float maxGeoX=transformer.getRotatedMaxGeoX();
  float minGeoX=transformer.getRotatedMinGeoX();
  float maxGeoY=transformer.getRotatedMaxGeoY();
  float minGeoY=transformer.getRotatedMinGeoY();
  long width=transformer.getRotatedBitmapW();
  long height=transformer.getRotatedBitmapH();
  float targetResolution=transformer.getGeoW() / width;
  GoogleLayerInfo.ResolutionInfo resolution=layerInfo.getNearestResolution(targetResolution);
  Map<String,List<String>> tileParams=new HashMap<String,List<String>>();
  double latitude;
  double longitude;
  double originShift=20037508.342789244;
  longitude=(((maxGeoX + minGeoX) / 2.0) / originShift) * 180.0;
  latitude=(((maxGeoY + minGeoY) / 2.0) / originShift) * 180.0;
  latitude=180 / Math.PI * (2 * Math.atan(Math.exp(latitude * Math.PI / 180.0)) - Math.PI / 2.0);
  DecimalFormat df=new DecimalFormat("#.#######################");
  String center=df.format(latitude) + "," + df.format(longitude);
  String size=Long.toString(width) + "x" + Long.toString(height);
  URIUtils.addParamOverride(tileParams,"center",center);
  URIUtils.addParamOverride(tileParams,"size",size);
  URIUtils.addParamOverride(tileParams,"zoom",Integer.toString(resolution.index));
  URI uri=URIUtils.addParams(commonUri,tileParams,OVERRIDE_ALL);
  List<URI> uris=new ArrayList<URI>(1);
  uris.add(config.signURI(uri));
  formatter.render(transformer,uris,parallelMapTileLoader,context,opacity,1,0,0,transformer.getRotatedBitmapW(),transformer.getRotatedBitmapH());
}
 

Example 81

From project mapfish-print_1, under directory /src/main/java/org/mapfish/print/map/readers/google/.

Source file: GoogleMapReader.java

  31 
vote

protected void renderTiles(TileRenderer formatter,Transformer transformer,URI commonUri,ParallelMapTileLoader parallelMapTileLoader) throws IOException, URISyntaxException {
  float maxGeoX=transformer.getRotatedMaxGeoX();
  float minGeoX=transformer.getRotatedMinGeoX();
  float maxGeoY=transformer.getRotatedMaxGeoY();
  float minGeoY=transformer.getRotatedMinGeoY();
  long width=transformer.getRotatedBitmapW();
  long height=transformer.getRotatedBitmapH();
  float targetResolution=transformer.getGeoW() / width;
  GoogleLayerInfo.ResolutionInfo resolution=layerInfo.getNearestResolution(targetResolution);
  Map<String,List<String>> tileParams=new HashMap<String,List<String>>();
  double latitude;
  double longitude;
  double originShift=20037508.342789244;
  longitude=(((maxGeoX + minGeoX) / 2.0) / originShift) * 180.0;
  latitude=(((maxGeoY + minGeoY) / 2.0) / originShift) * 180.0;
  latitude=180 / Math.PI * (2 * Math.atan(Math.exp(latitude * Math.PI / 180.0)) - Math.PI / 2.0);
  DecimalFormat df=new DecimalFormat("#.#######################");
  String center=df.format(latitude) + "," + df.format(longitude);
  String size=Long.toString(width) + "x" + Long.toString(height);
  URIUtils.addParamOverride(tileParams,"center",center);
  URIUtils.addParamOverride(tileParams,"size",size);
  URIUtils.addParamOverride(tileParams,"zoom",Integer.toString(resolution.index));
  URI uri=URIUtils.addParams(commonUri,tileParams,OVERRIDE_ALL);
  List<URI> uris=new ArrayList<URI>(1);
  uris.add(config.signURI(uri));
  formatter.render(transformer,uris,parallelMapTileLoader,context,opacity,1,0,0,transformer.getRotatedBitmapW(),transformer.getRotatedBitmapH());
}
 

Example 82

From project maven-shared, under directory /maven-shared-utils/src/main/java/org/apache/maven/shared/utils/io/.

Source file: FileUtils.java

  31 
vote

/** 
 * Create a temporary file in a given directory. <p/> <p>The file denoted by the returned abstract pathname did not exist before this method was invoked, any subsequent invocation of this method will yield a different file name.</p> <p/> The filename is prefixNNNNNsuffix where NNNN is a random number </p> <p>This method is different to  {@link File#createTempFile(String,String,File)} of JDK 1.2as it doesn't create the file itself. It uses the location pointed to by java.io.tmpdir when the parentDir attribute is null.</p> <p>To delete automatically the file created by this method, use the {@link File#deleteOnExit()} method.</p>
 * @param prefix    prefix before the random number
 * @param suffix    file extension; include the '.'
 * @param parentDir Directory to create the temporary file in <code>-java.io.tmpdir</code>used if not specificed
 * @return a File reference to the new temporary file.
 */
public static File createTempFile(@Nonnull String prefix,@Nonnull String suffix,@Nullable File parentDir){
  File result;
  String parent=System.getProperty("java.io.tmpdir");
  if (parentDir != null) {
    parent=parentDir.getPath();
  }
  DecimalFormat fmt=new DecimalFormat("#####");
  SecureRandom secureRandom=new SecureRandom();
  long secureInitializer=secureRandom.nextLong();
  Random rand=new Random(secureInitializer + Runtime.getRuntime().freeMemory());
  do {
    result=new File(parent,prefix + fmt.format(Math.abs(rand.nextInt())) + suffix);
  }
 while (result.exists());
  return result;
}
 

Example 83

From project Metamorphosis, under directory /metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/.

Source file: MetaStatLog.java

  31 
vote

private static String formatOutput(final StatCounter counter){
  final double count=counter.count.get();
  final double values=counter.value.get();
  final long duration=(System.currentTimeMillis() - lastResetTime) / 1000;
  String averageValueStr="invalid";
  String averageCountStr="invalid";
  final DecimalFormat numberFormat=new DecimalFormat("#.##");
  if (count != 0) {
    final double averageValue=values / count;
    averageValueStr=numberFormat.format(averageValue);
  }
  if (duration != 0) {
    final double averageCount=count / duration;
    averageCountStr=numberFormat.format(averageCount);
  }
  return String.format(OUTPUT_FORMAT,numberFormat.format(count),numberFormat.format(values),averageValueStr,averageCountStr,duration);
}
 

Example 84

From project mixare, under directory /plugins/mixare-library/src/org/mixare/lib/marker/draw/.

Source file: DrawTextBox.java

  31 
vote

@Override public void draw(PaintScreen dw){
  double distance=getDoubleProperty(PROPERTY_NAME_DISTANCE);
  String title=getStringProperty(PROPERTY_NAME_TITLE);
  TextObj textBlock=(TextObj)getParcelableProperty(PROPERTY_NAME_TEXTBLOCK);
  Boolean underline=getBooleanProperty(PROPERTY_NAME_UNDERLINE);
  Boolean visible=getBooleanProperty(PROPERTY_NAME_VISIBLE);
  MixVector signMarker=getMixVectorProperty(PROPERTY_NAME_SIGNMARKER);
  Label txtlab=(Label)getParcelableProperty(PROPERTY_NAME_TEXTLAB);
  if (txtlab == null) {
    txtlab=new Label();
  }
  float maxHeight=Math.round(dw.getHeight() / 10f) + 1;
  String textStr="";
  DecimalFormat df=new DecimalFormat("@#");
  if (distance < 1000.0) {
    textStr=title + " (" + df.format(distance)+ "m)";
  }
 else {
    distance=distance / 1000.0;
    textStr=title + " (" + df.format(distance)+ "km)";
  }
  textBlock=new TextObj(textStr,Math.round(maxHeight / 2f) + 1,250,dw,underline);
  if (visible) {
    if (distance < 100.0) {
      textBlock.setBgColor(Color.argb(128,52,52,52));
      textBlock.setBorderColor(Color.rgb(255,104,91));
    }
 else {
      textBlock.setBgColor(Color.argb(128,0,0,0));
      textBlock.setBorderColor(Color.rgb(255,255,255));
    }
    txtlab.prepare(textBlock);
    dw.setStrokeWidth(1f);
    dw.setFill(true);
    dw.paintObj(txtlab,signMarker.x - txtlab.getWidth() / 2,signMarker.y + maxHeight,0,1);
  }
}
 

Example 85

From project mtc, under directory /mtc-gui/src/main/java/org/drugis/mtc/gui/.

Source file: AnalysisView.java

  31 
vote

private JTextField createDoubleField(ValueHolder model){
  JTextField field=new JTextField(10);
  field.setHorizontalAlignment(JTextField.RIGHT);
  Bindings.bind(field,ConverterFactory.createStringConverter(model,new DecimalFormat("0.#####")),true);
  return field;
}
 

Example 86

From project mvel, under directory /src/test/java/org/mvel2/tests/perftests/.

Source file: SimpleTests.java

  31 
vote

private static void testQuickSortMVEL(PrintStream ps) throws IOException {
  double time;
  time=System.currentTimeMillis();
  char[] sourceFile=ParseTools.loadFromFile(new File("samples/scripts/quicksort.mvel"));
  Serializable c=MVEL.compileExpression(sourceFile);
  Map vars=new HashMap();
  DecimalFormat dc=new DecimalFormat("#.##");
  for (int a=0; a < 10000; a++) {
    vars.clear();
    MVEL.executeExpression(c,vars);
  }
  ps.println("Result: " + (time=System.currentTimeMillis() - time));
  ps.println("Rate  : " + (COUNT / (time / 1000)) + " per second.");
  ps.println("FreeMem: " + dc.format((double)getRuntime().freeMemory() / (1024d * 1024d)) + "MB / TotalMem: "+ dc.format((double)getRuntime().totalMemory() / (1024d * 1024d))+ "MB");
  ps.println("TotalGarbaged: " + DynamicOptimizer.totalRecycled);
}
 

Example 87

From project MyExpenses, under directory /tests/src/org/totschnig/myexpenses/test/.

Source file: UtilsTest.java

  31 
vote

public void testValidateNumber(){
  DecimalFormat nfDLocal;
  DecimalFormatSymbols symbols=new DecimalFormatSymbols();
  symbols.setDecimalSeparator('.');
  nfDLocal=new DecimalFormat("#0.###",symbols);
  Assert.assertEquals(0,Utils.validateNumber(nfDLocal,"4.7").compareTo(new BigDecimal("4.7")));
  Assert.assertNull(Utils.validateNumber(nfDLocal,"4,7"));
  symbols.setDecimalSeparator(',');
  nfDLocal=new DecimalFormat("#0.###",symbols);
  Assert.assertEquals(0,Utils.validateNumber(nfDLocal,"4,7").compareTo(new BigDecimal("4.7")));
  Assert.assertNull(Utils.validateNumber(nfDLocal,"4.7"));
  nfDLocal=new DecimalFormat("#0");
  nfDLocal.setParseIntegerOnly(true);
  Assert.assertEquals(0,Utils.validateNumber(nfDLocal,"470").compareTo(new BigDecimal(470)));
  Assert.assertNull(Utils.validateNumber(nfDLocal,"470.123"));
}
 

Example 88

From project myfaces-extcdi, under directory /jse-modules/message-module/impl/src/main/java/org/apache/myfaces/extensions/cdi/message/impl/formatter/.

Source file: DefaultNumberFormatter.java

  31 
vote

private NumberFormat getNumberFormat(Locale locale){
  DecimalFormatSymbols symbols=new DecimalFormatSymbols(locale);
  if (this.groupingSeparator != null) {
    symbols.setGroupingSeparator(this.groupingSeparator);
  }
  if (this.decimalSeparator != null) {
    symbols.setDecimalSeparator(this.decimalSeparator);
  }
  if (this.exponentSeparator != null) {
    symbols.setExponentSeparator(this.exponentSeparator);
  }
  return new DecimalFormat("",symbols);
}
 

Example 89

From project NFCShopping, under directory /mobile phone client/NFCShopping/src/scut/bgooo/concern/.

Source file: ConcernItemAdapter.java

  31 
vote

@Override public View getView(int position,View convertView,ViewGroup parent){
  if (mItems.get(position).getId() == 0) {
    convertView=LayoutInflater.from(mContext).inflate(R.layout.datetagitemview,null);
    TextView tv=(TextView)convertView.findViewById(R.id.tvDatetag);
    SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");
    Date scanDate=new Date(mItems.get(position).getTimestamp());
    String date=formater.format(scanDate);
    tv.setText(date);
  }
 else {
    convertView=LayoutInflater.from(mContext).inflate(R.layout.productitem,null);
    vh.mImageView=(ImageView)convertView.findViewById(R.id.goods_image);
    vh.mGoodScore=(RatingBar)convertView.findViewById(R.id.score);
    vh.mGoodsNmae=(TextView)convertView.findViewById(R.id.name);
    vh.mGoodsPrice=(TextView)convertView.findViewById(R.id.price);
    ConcernItem item=mItems.get(position);
    if (TaskHandler.allIcon.get(item.getProductId()) == null) {
      data=item.getIcon();
      bitmap=BitmapFactory.decodeByteArray(data,0,data.length);
      TaskHandler.allIcon.put(item.getProductId(),bitmap);
    }
 else {
      bitmap=TaskHandler.allIcon.get(item.getProductId());
    }
    vh.mImageView.setImageBitmap(bitmap);
    vh.mGoodScore.setRating(item.getRating());
    vh.mGoodsNmae.setText(item.getName());
    DecimalFormat df=new java.text.DecimalFormat("#0.00");
    vh.mGoodsPrice.setText(df.format(item.getPrice()) + "?");
  }
  return convertView;
}
 

Example 90

From project nutch, under directory /src/test/org/apache/nutch/segment/.

Source file: TestSegmentMerger.java

  31 
vote

public void setUp() throws Exception {
  conf=NutchConfiguration.create();
  fs=FileSystem.get(conf);
  long blkSize=fs.getDefaultBlockSize();
  testDir=new Path(conf.get("hadoop.tmp.dir"),"merge-" + System.currentTimeMillis());
  seg1=new Path(testDir,"seg1");
  seg2=new Path(testDir,"seg2");
  out=new Path(testDir,"out");
  System.err.println("Creating large segment 1...");
  DecimalFormat df=new DecimalFormat("0000000");
  Text k=new Text();
  Path ptPath=new Path(new Path(seg1,ParseText.DIR_NAME),"part-00000");
  MapFile.Writer w=new MapFile.Writer(conf,fs,ptPath.toString(),Text.class,ParseText.class);
  long curSize=0;
  countSeg1=0;
  while (curSize < blkSize * 2) {
    k.set("seg1-" + df.format(countSeg1));
    w.append(k,new ParseText("seg1 text " + countSeg1));
    countSeg1++;
    curSize+=40;
  }
  w.close();
  System.err.println(" - done: " + countSeg1 + " records.");
  System.err.println("Creating large segment 2...");
  ptPath=new Path(new Path(seg2,ParseText.DIR_NAME),"part-00000");
  w=new MapFile.Writer(conf,fs,ptPath.toString(),Text.class,ParseText.class);
  curSize=0;
  countSeg2=0;
  while (curSize < blkSize * 2) {
    k.set("seg2-" + df.format(countSeg2));
    w.append(k,new ParseText("seg2 text " + countSeg2));
    countSeg2++;
    curSize+=40;
  }
  w.close();
  System.err.println(" - done: " + countSeg2 + " records.");
}
 

Example 91

From project onebusaway-nyc, under directory /onebusaway-nyc-presentation/src/main/java/org/onebusaway/nyc/presentation/impl/realtime/.

Source file: SiriSupport.java

  31 
vote

private static OnwardCallStructure getOnwardCallStructure(StopBean stopBean,PresentationService presentationService,double distanceOfCallAlongTrip,double distanceOfVehicleFromCall,int visitNumber,int index,TimepointPredictionRecord prediction){
  OnwardCallStructure onwardCallStructure=new OnwardCallStructure();
  onwardCallStructure.setVisitNumber(BigInteger.valueOf(visitNumber));
  StopPointRefStructure stopPointRef=new StopPointRefStructure();
  stopPointRef.setValue(stopBean.getId());
  onwardCallStructure.setStopPointRef(stopPointRef);
  NaturalLanguageStringStructure stopPoint=new NaturalLanguageStringStructure();
  stopPoint.setValue(stopBean.getName());
  onwardCallStructure.setStopPointName(stopPoint);
  if (prediction != null) {
    onwardCallStructure.setExpectedArrivalTime(new Date(prediction.getTimepointPredictedTime()));
    onwardCallStructure.setExpectedDepartureTime(new Date(prediction.getTimepointPredictedTime()));
  }
  SiriExtensionWrapper wrapper=new SiriExtensionWrapper();
  ExtensionsStructure distancesExtensions=new ExtensionsStructure();
  SiriDistanceExtension distances=new SiriDistanceExtension();
  DecimalFormat df=new DecimalFormat();
  df.setMaximumFractionDigits(2);
  df.setGroupingUsed(false);
  distances.setStopsFromCall(index);
  distances.setCallDistanceAlongRoute(Double.valueOf(df.format(distanceOfCallAlongTrip)));
  distances.setDistanceFromCall(Double.valueOf(df.format(distanceOfVehicleFromCall)));
  distances.setPresentableDistance(presentationService.getPresentableDistance(distances));
  wrapper.setDistances(distances);
  distancesExtensions.setAny(wrapper);
  onwardCallStructure.setExtensions(distancesExtensions);
  return onwardCallStructure;
}
 

Example 92

From project onebusaway-uk, under directory /onebusaway-uk-atco-cif-to-gtfs-converter/src/main/java/org/onebusaway/uk/atco_cif_to_gtfs_converter/.

Source file: AtcoCifToGtfsConverter.java

  31 
vote

private String getServiceDateModificationsSuffix(JourneyHeaderElement journey){
  List<JourneyDateRunningElement> modifications=journey.getCalendarModifications();
  if (modifications.isEmpty()) {
    return "00";
  }
  StringBuilder b=new StringBuilder();
  Collections.sort(modifications);
  for (  JourneyDateRunningElement modification : modifications) {
    b.append('|');
    b.append(getServiceDate(modification.getStartDate()).getAsString());
    b.append('-');
    b.append(getServiceDate(modification.getEndDate()).getAsString());
    b.append('-');
    b.append(modification.getOperationCode());
  }
  String key=b.toString();
  String suffix=_serviceDateModificationSuffixByKey.get(key);
  if (suffix == null) {
    DecimalFormat format=new DecimalFormat("00");
    suffix=format.format(_serviceDateModificationSuffixByKey.size() + 1);
    _serviceDateModificationSuffixByKey.put(key,suffix);
  }
  return suffix;
}
 

Example 93

From project open-data-node, under directory /src/main/java/sk/opendata/odn/harvester/datanest/.

Source file: ProcurementsDatanestHarvester.java

  31 
vote

public ProcurementsDatanestHarvester() throws IOException, RepositoryConfigException, RepositoryException, ParserConfigurationException, TransformerConfigurationException {
  super(KEY_DATANEST_PROCUREMENTS_URL_KEY);
  ProcurementRdfSerializer rdfSerializer=new ProcurementRdfSerializer(SesameRepository.getInstance());
  addSerializer(rdfSerializer);
  SolrSerializer<ProcurementRecord> solrSerializer=new SolrSerializer<ProcurementRecord>(SolrRepository.getInstance());
  addSerializer(solrSerializer);
  priceFormat=new DecimalFormat();
  DecimalFormatSymbols symbols=new DecimalFormatSymbols();
  symbols.setGroupingSeparator(' ');
  symbols.setDecimalSeparator(',');
  priceFormat.setDecimalFormatSymbols(symbols);
}
 

Example 94

From project chililog-server, under directory /src/main/java/org/chililog/server/engine/parsers/.

Source file: DoubleFieldParser.java

  30 
vote

/** 
 * Constructor
 * @param repoFieldInfo Field meta data
 * @throws ParseException
 */
public DoubleFieldParser(RepositoryFieldConfigBO repoFieldInfo) throws ParseException {
  super(repoFieldInfo);
  Hashtable<String,String> properties=repoFieldInfo.getProperties();
  String d=properties.get(RepositoryFieldConfigBO.DEFAULT_VALUE_PROPERTY_NAME);
  String s=properties.get(RepositoryFieldConfigBO.NUMBER_FORMAT_PROPERTY_NAME);
  if (!StringUtils.isBlank(s)) {
    _numberFormatter=new DecimalFormat(s);
  }
  if (!StringUtils.isBlank(d)) {
    if (_numberFormatter == null) {
      _defaultValue=Double.parseDouble(d);
    }
 else {
      _defaultValue=_numberFormatter.parse(d).doubleValue();
    }
  }
}
 

Example 95

From project dawn-third, under directory /org.dawb.org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/.

Source file: AbstractScale.java

  30 
vote

private void setFormat(String formatPattern){
  try {
    new DecimalFormat(formatPattern);
  }
 catch (  NullPointerException e) {
    throw e;
  }
catch (  IllegalArgumentException e) {
    throw e;
  }
  cachedFormat=null;
  this.formatPattern=formatPattern;
  autoFormat=false;
  setDirty(true);
  revalidate();
  repaint();
}
 

Example 96

From project Dream, under directory /WEB-INF/src/java/org/campware/dream/modules/screens/.

Source file: CreamForm.java

  30 
vote

/** 
 * Grab a record from the database based on the entry_id found in the form. Make the data available in the template.
 */
public void doBuildTemplate(RunData data,Context context){
  try {
    myData=data;
    int entry_id=data.getParameters().getInt(defFormIdName);
    if (entry_id > 0) {
      Criteria criteria=new Criteria();
      criteria.add(defIdName,entry_id);
      getEntry(criteria,context);
      context.put("mode","update");
    }
 else     if (entry_id < 0) {
      getNewRelated(entry_id * (-1),context);
      context.put("mode","insert");
    }
 else {
      getNew(context);
      context.put("mode","insert");
    }
    getLookups(context);
    context.put("df",new SimpleDateFormat("dd.MM.yyyy"));
    context.put("dtf",new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"));
    context.put("dstf",new SimpleDateFormat("dd.MM.yyyy HH:mm"));
    DecimalFormatSymbols symb=new DecimalFormatSymbols();
    symb.setDecimalSeparator('.');
    context.put("af",new DecimalFormat("0.00",symb));
    context.put("rf",new DecimalFormat("0.000000",symb));
    context.put("today",new Date());
    Date nowTime=new Date();
    nowTime.setHours(12);
    nowTime.setMinutes(5);
    context.put("now",nowTime);
  }
 catch (  Exception e) {
  }
}
 

Example 97

From project gh4a, under directory /src/com/gh4a/utils/.

Source file: StringUtils.java

  30 
vote

public static String toHumanReadbleFormat(long size){
  NumberFormat nf=new DecimalFormat("0.#");
  String s;
  float f;
  if (size / (1024 * 1024) > 0) {
    f=size;
    s=nf.format(f / (1024 * 1024)) + " GB";
  }
 else   if (size / (1024) > 0) {
    f=size;
    s=nf.format(f / (1024)) + " MB";
  }
 else {
    f=size;
    s=nf.format(f) + " bytes";
  }
  return s;
}
 

Example 98

From project incubator, under directory /net.karlmartens.ui/test/net/karlmartens/ui/viewer/.

Source file: TimeSeriesTableViewerTest.java

  30 
vote

@Override public TimeSeriesTableViewer run(Shell shell){
  final Display display=shell.getDisplay();
  final TimeSeriesTableViewer viewer=TimeSeriesTableViewer.newTimeSeriesTable(shell);
  viewer.setLabelProvider(new TestColumnLabelProvider(0));
  viewer.setEditingSupport(new TestTimeSeriesEditingSupport(new DecimalFormat("#,##0.0000"),3));
  viewer.setDateFormat(new LocalDateFormat(DateTimeFormat.forPattern("MMM yyyy")));
  viewer.setNumberFormat(new DecimalFormat("#,##0.00"));
  viewer.setScrollDataMode(ScrollDataMode.SELECTED_ROWS);
  final TableViewerColumn c1=new TableViewerColumn(viewer,SWT.NONE);
  c1.setLabelProvider(new TestColumnLabelProvider(0));
  c1.setEditingSupport(new TestTextEditingSupport(viewer,0,SWT.LEFT));
  c1.getColumn().setText("Test");
  c1.getColumn().setWidth(75);
  final TableViewerColumn c2=new TableViewerColumn(viewer,SWT.CHECK);
  c2.setLabelProvider(new TestColumnLabelProvider(1));
  c2.setEditingSupport(new TestBooleanEditingSupport(viewer,1));
  c2.getColumn().setText("Test 2");
  c2.getColumn().setWidth(60);
  final Table table=viewer.getControl();
  table.setHeaderVisible(true);
  table.setFixedColumnCount(2);
  table.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
  table.setFont(new Font(display,"Arial",8,SWT.NORMAL));
  table.addColumnSortSupport();
  viewer.setContentProvider(new TestTimeSeriesContentProvider(_dates,3));
  viewer.setInput(_input);
  return viewer;
}
 

Example 99

From project liquidroid, under directory /src/liqui/droid/util/.

Source file: StringUtils.java

  30 
vote

/** 
 * To human readble format.
 * @param size the size
 * @return the string
 */
public static String toHumanReadbleFormat(long size){
  NumberFormat nf=new DecimalFormat("0.#");
  String s;
  float f;
  if (size / (1024 * 1024) > 0) {
    f=size;
    s=nf.format(f / (1024 * 1024)) + " GB";
  }
 else   if (size / (1024) > 0) {
    f=size;
    s=nf.format(f / (1024)) + " MB";
  }
 else {
    f=size;
    s=nf.format(f) + " bytes";
  }
  return s;
}
 

Example 100

From project Mobile-Tour-Guide, under directory /zxing-2.0/core/src/com/google/zxing/maxicode/decoder/.

Source file: DecodedBitStreamParser.java

  30 
vote

static DecoderResult decode(byte[] bytes,int mode){
  StringBuilder result=new StringBuilder(144);
switch (mode) {
case 2:
case 3:
    String postcode;
  if (mode == 2) {
    int pc=getPostCode2(bytes);
    NumberFormat df=new DecimalFormat("0000000000".substring(0,getPostCode2Length(bytes)));
    postcode=df.format(pc);
  }
 else {
    postcode=getPostCode3(bytes);
  }
String country=THREE_DIGITS.format(getCountry(bytes));
String service=THREE_DIGITS.format(getServiceClass(bytes));
result.append(getMessage(bytes,10,84));
if (result.toString().startsWith("[)>" + RS + "01"+ GS)) {
result.insert(9,postcode + GS + country+ GS+ service+ GS);
}
 else {
result.insert(0,postcode + GS + country+ GS+ service+ GS);
}
break;
case 4:
result.append(getMessage(bytes,1,93));
break;
case 5:
result.append(getMessage(bytes,1,77));
break;
}
return new DecoderResult(bytes,result.toString(),null,String.valueOf(mode));
}
 

Example 101

From project clearcase-plugin, under directory /src/main/java/hudson/plugins/clearcase/.

Source file: AbstractClearCaseScm.java

  29 
vote

public AbstractClearCaseScm(final String viewName,final String mkviewOptionalParam,final boolean filterOutDestroySubBranchEvent,final boolean useUpdate,final boolean rmviewonrename,final String excludedRegions,final boolean useDynamicView,final String viewDrive,boolean extractLoadRules,final String loadRules,final boolean useOtherLoadRulesForPolling,final String loadRulesForPolling,final String multiSitePollBuffer,final boolean createDynView,final boolean freezeCode,final boolean recreateView,final String viewPath,ChangeSetLevel changeset,ViewStorageFactory viewStorageFactory){
  Validate.notNull(viewName);
  this.viewName=viewName;
  this.mkviewOptionalParam=mkviewOptionalParam;
  this.filteringOutDestroySubBranchEvent=filterOutDestroySubBranchEvent;
  this.useUpdate=useUpdate;
  this.removeViewOnRename=rmviewonrename;
  this.excludedRegions=excludedRegions;
  this.useDynamicView=useDynamicView;
  this.viewDrive=viewDrive;
  this.extractLoadRules=extractLoadRules;
  this.loadRules=loadRules;
  this.useOtherLoadRulesForPolling=useOtherLoadRulesForPolling;
  this.loadRulesForPolling=loadRulesForPolling;
  if (multiSitePollBuffer != null) {
    try {
      this.multiSitePollBuffer=DecimalFormat.getIntegerInstance().parse(multiSitePollBuffer).intValue();
    }
 catch (    ParseException e) {
      this.multiSitePollBuffer=0;
    }
  }
 else {
    this.multiSitePollBuffer=0;
  }
  this.createDynView=createDynView;
  this.freezeCode=freezeCode;
  this.recreateView=recreateView;
  this.viewPath=StringUtils.defaultIfEmpty(viewPath,viewName);
  this.changeset=changeset;
  this.viewStorageFactory=viewStorageFactory;
}
 

Example 102

From project contribution_eevolution_costing_engine, under directory /extension/costengine/src/test/java/org/adempiere/.

Source file: CSVFactory.java

  29 
vote

public Collection<MMScenario> read(InputStream in) throws Exception {
  ArrayList<MMScenario> tests=new ArrayList<MMScenario>();
  reader=new CsvListReader(new InputStreamReader(in),CsvPreference.STANDARD_PREFERENCE);
  String[] header=getCSVHeader();
  List<String> line;
  int last_lineNo=-1;
  MMScenario scenario=null;
  try {
    while ((line=reader.read()) != null) {
      if (last_lineNo == -1 || last_lineNo + 1 < reader.getLineNumber()) {
        if (scenario != null) {
          tests.add(scenario);
        }
        scenario=new MMScenario("junit-test-line_" + (new DecimalFormat("000").format(reader.getLineNumber())));
      }
      readDocument(scenario,header,line);
      last_lineNo=reader.getLineNumber();
    }
  }
 catch (  Exception e) {
    throw new RuntimeException("Error on line " + reader.getLineNumber() + ": "+ e.getLocalizedMessage(),e);
  }
  if (scenario != null) {
    tests.add(scenario);
  }
  return tests;
}
 

Example 103

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/feed/objects/.

Source file: LocationObj.java

  29 
vote

@Override public void render(Context context,ViewGroup frame,Obj obj,boolean allowInteractions){
  JSONObject content=obj.getJson();
  TextView valueTV=new TextView(context);
  NumberFormat df=DecimalFormat.getNumberInstance();
  df.setMaximumFractionDigits(5);
  df.setMinimumFractionDigits(5);
  String msg="I'm at " + df.format(content.optDouble(COORD_LAT)) + ", "+ df.format(content.optDouble(COORD_LONG));
  valueTV.setText(msg);
  valueTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
  valueTV.setGravity(Gravity.TOP | Gravity.LEFT);
  frame.addView(valueTV);
}
 

Example 104

From project echo3, under directory /src/server-java/app/nextapp/echo/app/serial/property/.

Source file: NumberPeer.java

  29 
vote

/** 
 * @see nextapp.echo.app.serial.SerialPropertyPeer#toProperty(nextapp.echo.app.util.Context,java.lang.Class,org.w3c.dom.Element)
 */
public Object toProperty(Context context,Class objectClass,Element propertyElement) throws SerialException {
  String valueText=propertyElement.hasAttribute("v") ? propertyElement.getAttribute("v") : DomUtil.getElementText(propertyElement);
  try {
    return DecimalFormat.getInstance().parseObject(valueText);
  }
 catch (  ParseException ex) {
    throw new SerialException("Cannot parse as number: " + valueText,ex);
  }
}
 

Example 105

From project etherpad, under directory /infrastructure/net.appjet.common/util/.

Source file: LenientFormatter.java

  29 
vote

FloatUtil(StringBuilder result,FormatToken formatToken,DecimalFormat decimalFormat,Object argument){
  this.result=result;
  this.formatToken=formatToken;
  this.decimalFormat=decimalFormat;
  this.argument=argument;
  this.minusSign=decimalFormat.getDecimalFormatSymbols().getMinusSign();
}
 

Example 106

From project indextank-engine, under directory /lucene-experimental/com/flaptor/org/apache/lucene/util/.

Source file: RamUsageEstimator.java

  29 
vote

/** 
 * Return good default units based on byte size.
 */
public static String humanReadableUnits(long bytes,DecimalFormat df){
  String newSizeAndUnits;
  if (bytes / ONE_GB > 0) {
    newSizeAndUnits=String.valueOf(df.format((float)bytes / ONE_GB)) + " GB";
  }
 else   if (bytes / ONE_MB > 0) {
    newSizeAndUnits=String.valueOf(df.format((float)bytes / ONE_MB)) + " MB";
  }
 else   if (bytes / ONE_KB > 0) {
    newSizeAndUnits=String.valueOf(df.format((float)bytes / ONE_KB)) + " KB";
  }
 else {
    newSizeAndUnits=String.valueOf(bytes) + " bytes";
  }
  return newSizeAndUnits;
}
 

Example 107

From project jBilling, under directory /src/java/com/sapienter/jbilling/server/util/.

Source file: Util.java

  29 
vote

public static String formatMoney(BigDecimal number,Integer userId,Integer currencyId,boolean forEmail) throws SessionInternalError {
  try {
    UserBL user=new UserBL(userId);
    Locale locale=user.getLocale();
    ResourceBundle bundle=ResourceBundle.getBundle("entityNotifications",locale);
    NumberFormat format=NumberFormat.getNumberInstance(locale);
    ((DecimalFormat)format).applyPattern(bundle.getString("format.float"));
    CurrencyBL currency=new CurrencyBL(currencyId);
    String symbol=currency.getEntity().getSymbol();
    if (symbol.length() >= 4 && symbol.charAt(0) == '&' && symbol.charAt(1) == '#') {
      if (!forEmail) {
        symbol=symbol.substring(2);
        symbol=symbol.substring(0,symbol.length() - 1);
        Character ch=(char)Integer.valueOf(symbol).intValue();
        symbol=ch.toString();
      }
 else {
        symbol=currency.getEntity().getCode();
      }
    }
    return symbol + " " + format.format(number.doubleValue());
  }
 catch (  Exception e) {
    throw new SessionInternalError(e);
  }
}
 

Example 108

From project joda-money, under directory /src/main/java/org/joda/money/format/.

Source file: MoneyAmountStyle.java

  29 
vote

/** 
 * Gets the prototype localized style for the given locale. <p> This uses  {@link DecimalFormatSymbols} and {@link NumberFormat}. <p> If JDK 6 or newer is being used,  {@code DecimalFormatSymbols.getInstance(locale)}will be used in order to allow the use of locales defined as extensions. Otherwise,  {@code new DecimalFormatSymbols(locale)} will be used.
 * @param locale  the {@link Locale} used to get the correct {@link DecimalFormatSymbols}
 * @return the symbols, never null
 */
private static MoneyAmountStyle getLocalizedStyle(Locale locale){
  MoneyAmountStyle protoStyle=LOCALIZED_CACHE.get(locale);
  if (protoStyle == null) {
    DecimalFormatSymbols symbols;
    try {
      Method method=DecimalFormatSymbols.class.getMethod("getInstance",new Class[]{Locale.class});
      symbols=(DecimalFormatSymbols)method.invoke(null,new Object[]{locale});
    }
 catch (    Exception ex) {
      symbols=new DecimalFormatSymbols(locale);
    }
    NumberFormat format=NumberFormat.getCurrencyInstance(locale);
    int size=(format instanceof DecimalFormat ? ((DecimalFormat)format).getGroupingSize() : 3);
    protoStyle=new MoneyAmountStyle(symbols.getZeroDigit(),'+',symbols.getMinusSign(),symbols.getMonetaryDecimalSeparator(),symbols.getGroupingSeparator(),size,true,false);
    LOCALIZED_CACHE.putIfAbsent(locale,protoStyle);
  }
  return protoStyle;
}
 

Example 109

From project logsaw-app, under directory /net.sf.logsaw.ui/src/net/sf/logsaw/ui/commands/handlers/.

Source file: SynchronizeLogResourceHandler.java

  29 
vote

private void doSynchronize(final ILogResource log) throws CoreException {
  UIPlugin.getDefault().getLogResourceManager().synchronize(log,new IGenericCallback<SynchronizationResult>(){
    @Override public void doCallback(    final SynchronizationResult payload){
      Display.getDefault().asyncExec(new Runnable(){
        @Override public void run(){
          IWorkbenchPage page=PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
          IEditorReference[] editorRefs=page.findEditors((IEditorInput)log.getAdapter(IEditorInput.class),null,IWorkbenchPage.MATCH_INPUT);
          for (          IEditorReference editorRef : editorRefs) {
            IEditorPart editorPart=editorRef.getEditor(false);
            ILogViewEditor editor=editorPart != null ? (ILogViewEditor)editorPart.getAdapter(ILogViewEditor.class) : null;
            if (editor != null) {
              editor.clearQueryContext();
              editor.refresh();
            }
          }
          NumberFormat fmt=DecimalFormat.getInstance();
          String title=payload.isCanceled() ? Messages.SynchronizeLogResourceAction_canceled_title : Messages.SynchronizeLogResourceAction_finished_title;
          String message=payload.isCanceled() ? Messages.SynchronizeLogResourceAction_canceled_message : Messages.SynchronizeLogResourceAction_finished_message;
          message=NLS.bind(message,new Object[]{log.getName(),UIUtils.formatRuntime(payload.getRuntime()),fmt.format(payload.getNumberOfEntriesAdded())});
          if (payload.getMessages().isEmpty()) {
            MessageDialog.openInformation(Display.getDefault().getActiveShell(),title,message);
          }
 else {
            IStatus status=new MultiStatus(UIPlugin.PLUGIN_ID,0,payload.getMessages().toArray(new IStatus[0]),message,null);
            StatusManager.getManager().handle(status,StatusManager.BLOCK);
          }
        }
      }
);
    }
  }
);
}
 

Example 110

From project mateo, under directory /src/main/java/mx/edu/um/mateo/activos/dao/impl/.

Source file: ActivoDaoHibernate.java

  29 
vote

private String getFolio(Empresa empresa){
  Query query=currentSession().createQuery("select f from FolioActivo f where f.nombre = :nombre and f.organizacion.id = :organizacionId");
  query.setString("nombre","ACTIVOS");
  query.setLong("organizacionId",empresa.getOrganizacion().getId());
  query.setLockOptions(LockOptions.UPGRADE);
  FolioActivo folio=(FolioActivo)query.uniqueResult();
  if (folio == null) {
    folio=new FolioActivo("ACTIVOS");
    folio.setOrganizacion(empresa.getOrganizacion());
    currentSession().save(folio);
    return getFolio(empresa);
  }
  folio.setValor(folio.getValor() + 1);
  java.text.NumberFormat nf=java.text.DecimalFormat.getInstance();
  nf.setGroupingUsed(false);
  nf.setMinimumIntegerDigits(7);
  nf.setMaximumIntegerDigits(7);
  nf.setMaximumFractionDigits(0);
  StringBuilder sb=new StringBuilder();
  sb.append("A-");
  sb.append(empresa.getOrganizacion().getCodigo());
  sb.append(empresa.getCodigo());
  sb.append(nf.format(folio.getValor()));
  return sb.toString();
}