Java Code Examples for java.text.NumberFormat

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 android_7, under directory /src/org/immopoly/android/fragments/.

Source file: MapFragment.java

  18 
vote

public void updateHud(Intent data,int element){
  if (mapButton != null) {
    mapButton.setSelected(true);
  }
  if (hudText != null) {
    NumberFormat nFormat=NumberFormat.getCurrencyInstance(Locale.GERMANY);
    nFormat.setMinimumIntegerDigits(1);
    nFormat.setMaximumFractionDigits(2);
    hudText.setText(nFormat.format(ImmopolyUser.getInstance().getBalance()));
  }
}
 

Example 2

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/util/.

Source file: DateUtils.java

  18 
vote

private static String doubleToString(double val,int maxFractionDigits,int minFractionDigits){
  NumberFormat f=NumberFormat.getNumberInstance(Locale.US);
  f.setMaximumFractionDigits(maxFractionDigits);
  f.setMinimumFractionDigits(minFractionDigits);
  return f.format(val);
}
 

Example 3

From project aws-tasks, under directory /src/main/java/datameer/awstasks/ssh/.

Source file: JschCommand.java

  18 
vote

protected final static void logStats(long timeStarted,long timeEnded,long totalLength){
  double durationInSec=(timeEnded - timeStarted) / 1000.0;
  NumberFormat format=NumberFormat.getNumberInstance();
  format.setMaximumFractionDigits(2);
  format.setMinimumFractionDigits(1);
  LOG.debug("File transfer time: " + format.format(durationInSec) + " Average Rate: "+ format.format(totalLength / durationInSec)+ " B/s");
}
 

Example 4

From project azkaban, under directory /azkaban-common/src/java/azkaban/common/web/.

Source file: GuiUtils.java

  18 
vote

public String displayBytes(long sizeBytes){
  NumberFormat nf=NumberFormat.getInstance();
  nf.setMaximumFractionDigits(2);
  if (sizeBytes >= ONE_TB)   return nf.format(sizeBytes / (double)ONE_TB) + " tb";
 else   if (sizeBytes >= ONE_GB)   return nf.format(sizeBytes / (double)ONE_GB) + " gb";
 else   if (sizeBytes >= ONE_MB)   return nf.format(sizeBytes / (double)ONE_MB) + " mb";
 else   if (sizeBytes >= ONE_KB)   return nf.format(sizeBytes / (double)ONE_KB) + " kb";
 else   return sizeBytes + " B";
}
 

Example 5

From project CircDesigNA, under directory /src/org/apache/commons/math/fraction/.

Source file: AbstractFormat.java

  18 
vote

/** 
 * Create a default number format.  The default number format is based on {@link NumberFormat#getNumberInstance(java.util.Locale)} with the onlycustomizing is the maximum number of BigFraction digits, which is set to 0.
 * @param locale the specific locale used by the format.
 * @return the default number format specific to the given locale.
 */
protected static NumberFormat getDefaultNumberFormat(final Locale locale){
  final NumberFormat nf=NumberFormat.getNumberInstance(locale);
  nf.setMaximumFractionDigits(0);
  nf.setParseIntegerOnly(true);
  return nf;
}
 

Example 6

From project CoinFlip, under directory /src/com/banasiak/coinflip/.

Source file: SelfTest.java

  18 
vote

public void updateDialog(SelfTestStatus taskStatus){
  final NumberFormat percentFormat=NumberFormat.getPercentInstance();
  percentFormat.setMaximumFractionDigits(1);
  headsValue.setText(Integer.toString(taskStatus.getHeads()));
  headsRatio.setText("(" + percentFormat.format(taskStatus.getHeadsPercentage()) + ")");
  tailsValue.setText(Integer.toString(taskStatus.getTails()));
  tailsRatio.setText("(" + percentFormat.format(taskStatus.getTailsPercentage()) + ")");
  totalValue.setText(Integer.toString(taskStatus.getTotal()));
  totalRatio.setText("(" + percentFormat.format(taskStatus.getCompletionPercentage()) + ")");
  elapsedTime.setText(Long.toString(taskStatus.getElapsedTime()));
}
 

Example 7

From project Danroth, under directory /src/main/java/org/yaml/snakeyaml/serializer/.

Source file: Serializer.java

  18 
vote

private String generateAnchor(){
  this.lastAnchorId++;
  NumberFormat format=NumberFormat.getNumberInstance();
  format.setMinimumIntegerDigits(3);
  format.setGroupingUsed(false);
  String anchorId=format.format(this.lastAnchorId);
  return "id" + anchorId;
}
 

Example 8

From project datasalt-utils, under directory /src/contrib/java/org/apache/solr/hadoop/.

Source file: SolrRecordWriter.java

  18 
vote

private String getOutFileName(TaskAttemptContext context,String prefix){
  TaskID taskId=context.getTaskAttemptID().getTaskID();
  int partition=taskId.getId();
  NumberFormat nf=NumberFormat.getInstance();
  nf.setMinimumIntegerDigits(5);
  nf.setGroupingUsed(false);
  StringBuilder result=new StringBuilder();
  result.append(prefix);
  result.append("-");
  result.append(nf.format(partition));
  return result.toString();
}
 

Example 9

From project dawn-ui, under directory /org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/.

Source file: RegionArea.java

  18 
vote

public void setStatusLineManager(final IStatusLineManager statusLine){
  if (statusLine == null)   return;
  final NumberFormat format=new DecimalFormat("#0.0000#");
  addMouseMotionListener(new MouseMotionListener.Stub(){
    @Override public void mouseMoved(    MouseEvent me){
      double x=getRegionGraph().primaryXAxis.getPositionValue(me.x,false);
      double y=getRegionGraph().primaryYAxis.getPositionValue(me.y,false);
      statusLine.setMessage(format.format(x) + ", " + format.format(y));
    }
  }
);
}
 

Example 10

From project des, under directory /daemon/lib/apache-log4j-1.2.16/tests/src/java/org/apache/log4j/.

Source file: TestLogMF.java

  18 
vote

/** 
 * Test LogMF.trace with single field pattern with float argument.
 */
public void testTraceFloat(){
  LogCapture capture=new LogCapture(TRACE);
  logger.setLevel(TRACE);
  float val=3.14f;
  NumberFormat format=NumberFormat.getInstance();
  LogMF.trace(logger,"Iteration {0}",val);
  assertEquals("Iteration " + format.format(val),capture.getMessage());
}
 

Example 11

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/records/.

Source file: JobId.java

  18 
vote

@Override public NumberFormat initialValue(){
  NumberFormat fmt=NumberFormat.getInstance();
  fmt.setGroupingUsed(false);
  fmt.setMinimumIntegerDigits(4);
  return fmt;
}
 

Example 12

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

Source file: LocationObj.java

  18 
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 13

From project ehour, under directory /eHour-service/src/main/java/net/rrm/ehour/mail/service/.

Source file: MailServiceImpl.java

  18 
vote

public void mailPMFixedAllottedReached(AssignmentAggregateReportElement assignmentAggregate,Date bookDate,User user){
  String subject;
  StringBuilder body=new StringBuilder();
  NumberFormat numberFormat=NumberFormat.getNumberInstance();
  SimpleDateFormat dateFormat=new SimpleDateFormat("dd MMM yyyy");
  subject="eHour: All allotted hours used for project " + assignmentAggregate.getProjectAssignment().getProject().getFullName() + " by "+ assignmentAggregate.getProjectAssignment().getUser().getFirstName()+ " "+ assignmentAggregate.getProjectAssignment().getUser().getLastName();
  body.append("Project warning for project " + assignmentAggregate.getProjectAssignment().getProject().getFullName() + " ("+ assignmentAggregate.getProjectAssignment().getProject().getCustomer().getName()+ ")"+ "\r\n\r\n");
  body.append(numberFormat.format(assignmentAggregate.getProjectAssignment().getAllottedHours().floatValue()) + " hours were allotted for this project to " + assignmentAggregate.getProjectAssignment().getUser().getFirstName()+ " "+ assignmentAggregate.getProjectAssignment().getUser().getLastName()+ "."+ "\r\n");
  body.append("On " + dateFormat.format(bookDate) + ", a total of "+ numberFormat.format(assignmentAggregate.getHours())+ " hours were booked reaching the allotted hours mark."+ "\r\n\r\n");
  body.append("Take note, " + assignmentAggregate.getProjectAssignment().getUser().getFirstName() + " "+ assignmentAggregate.getProjectAssignment().getUser().getLastName()+ " can't book anymore hours on the project. Add more hours in the project assignment if needed.");
  mailPMAggregateMessage(assignmentAggregate,subject,body.toString(),EhourConstants.MAILTYPE_FIXED_ALLOTTED_REACHED,bookDate,user);
}
 

Example 14

From project encog-java-core, under directory /src/main/java/org/encog/util/.

Source file: Format.java

  18 
vote

/** 
 * Format a percent. Using 6 decimal places.
 * @param e The percent to format.
 * @return The formatted percent.
 */
public static String formatPercent(final double e){
  if (Double.isNaN(e) || Double.isInfinite(e))   return "NaN";
  final NumberFormat f=NumberFormat.getPercentInstance();
  f.setMinimumFractionDigits(6);
  return f.format(e);
}
 

Example 15

From project entando-core-engine, under directory /src/main/java/com/agiletec/aps/system/common/entity/model/attribute/.

Source file: NumberAttribute.java

  18 
vote

/** 
 * Return the number in the format used for the current language, expressed in form of percentage. Using this method, a fractional number like. eg., 0.53 is displayed as 53%. 
 * @return The formatted number.
 */
public String getPercentNumber(){
  String number="";
  if (null != this.getNumber()) {
    NumberFormat numberInstance=NumberFormat.getPercentInstance(new Locale(getRenderingLang(),""));
    number=numberInstance.format(this.getNumber());
  }
  return number;
}
 

Example 16

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

Source file: AddItemToCargoDialog.java

  18 
vote

@Override protected void onCreateSimpleDialog(View inflatedLayout,Bundle savedInstanceState){
  this.inflatedLayout=inflatedLayout;
  Spinner itemSpinner=(Spinner)inflatedLayout.findViewById(R.id.item_spinner);
  adapter=new SimpleCursorAdapter(getActivity(),android.R.layout.simple_dropdown_item_1line,null,SPINNER_CURSOR_COLUMNS,SPINNER_VIEW_IDS,SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
  itemSpinner.setAdapter(adapter);
  itemSpinner.setOnItemSelectedListener(new AddItemOnItemSelectedListenet());
  NumberFormat nf=new DecimalFormat(EOITConst.VALUES_PATTERN);
  EditText editText=(EditText)inflatedLayout.findViewById(R.id.item_quantity);
  editText.setText(nf.format(quantity));
  editText.setOnKeyListener(new ItemQuantityOnKeyListener());
}
 

Example 17

From project farebot, under directory /src/com/codebutler/farebot/transit/.

Source file: EZLinkTransitData.java

  18 
vote

@Override public String getFareString(){
  NumberFormat numberFormat=NumberFormat.getCurrencyInstance();
  numberFormat.setCurrency(Currency.getInstance("SGD"));
  int balance=-mTransaction.getAmount();
  if (balance < 0)   return "Credit " + numberFormat.format(-balance / 100.0);
 else   return numberFormat.format(balance / 100.0);
}
 

Example 18

From project fastjson, under directory /src/test/java/com/alibaba/json/test/benchmark/.

Source file: BenchmarkExecutor.java

  18 
vote

public void handleResult(Codec codec,Result result){
  if (result.getError() != null) {
    result.getError().printStackTrace();
    return;
  }
  NumberFormat format=NumberFormat.getInstance();
  System.out.println(result.getName() + "\t" + codec.getName()+ "\t"+ format.format(result.getMillis())+ "\tYoungGC "+ result.getYoungGC()+ "\tFullGC "+ result.getFullGC());
}
 

Example 19

From project gmc, under directory /src/org.gluster.storage.management.core/src/org/gluster/storage/management/core/utils/.

Source file: NumberUtil.java

  18 
vote

public static final String formatNumber(double num){
  NumberFormat formatter=NumberFormat.getNumberInstance();
  formatter.setMinimumFractionDigits(2);
  formatter.setMaximumFractionDigits(2);
  return formatter.format(num);
}
 

Example 20

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

Source file: Money.java

  18 
vote

/** 
 * Returns a string representation of the Money object formatted according to  the <code>locale</code> and includes the currency symbol.  The output precision is limited to  {@link #DECIMAL_PLACES}.
 * @param locale Locale to use when formatting the object
 * @return String containing formatted Money representation
 */
public String formattedString(Locale locale){
  NumberFormat formatter=NumberFormat.getInstance(locale);
  formatter.setMinimumFractionDigits(DECIMAL_PLACES);
  formatter.setMaximumFractionDigits(DECIMAL_PLACES);
  return formatter.format(asDouble()) + " " + mCurrency.getSymbol(locale);
}
 

Example 21

From project hama, under directory /core/src/main/java/org/apache/hama/bsp/.

Source file: FileOutputFormat.java

  18 
vote

/** 
 * Helper function to generate a name that is unique for the task.
 * @param conf the configuration for the job.
 * @param name the name to make unique.
 * @return a unique name accross all tasks of the job.
 */
public static String getUniqueName(BSPJob conf,String name){
  int partition=conf.getInt("bsp.task.partition",-1);
  if (partition == -1) {
    throw new IllegalArgumentException("This method can only be called from within a Job");
  }
  NumberFormat numberFormat=NumberFormat.getInstance();
  numberFormat.setMinimumIntegerDigits(5);
  numberFormat.setGroupingUsed(false);
  return name + "-" + numberFormat.format(partition);
}
 

Example 22

From project hcatalog, under directory /src/java/org/apache/hcatalog/data/transfer/state/.

Source file: DefaultStateProvider.java

  18 
vote

/** 
 * Default implementation. Here, ids are generated randomly.
 */
@Override public int getId(){
  NumberFormat numberFormat=NumberFormat.getInstance();
  numberFormat.setMinimumIntegerDigits(5);
  numberFormat.setGroupingUsed(false);
  return Integer.parseInt(numberFormat.format(Math.abs(new Random().nextInt())));
}
 

Example 23

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

Source file: ArchiveUtils.java

  18 
vote

private static String doubleToString(double val,int maxFractionDigits,int minFractionDigits){
  if (Double.isNaN(val)) {
    return "NaN";
  }
  NumberFormat f=NumberFormat.getNumberInstance(Locale.US);
  f.setMaximumFractionDigits(maxFractionDigits);
  f.setMinimumFractionDigits(minFractionDigits);
  return f.format(val);
}
 

Example 24

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

Source file: TimeDialog.java

  18 
vote

public CustomTextField(){
  super(new NumberFormatter());
  NumberFormat nf=NumberFormat.getNumberInstance();
  nf.setParseIntegerOnly(true);
  NumberFormatter numberFormatter=new NumberFormatter(nf);
  this.setFormatter(numberFormatter);
  this.setValue(0);
  this.addFocusListener(this);
  ((DefaultFormatter)this.getFormatter()).setAllowsInvalid(false);
}
 

Example 25

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

Source file: TimeSeriesTableValueEditingSupport.java

  18 
vote

@Override protected void initializeCellEditorValue(CellEditor cellEditor,ViewerCell cell){
  cellEditor.setValue("");
  final TimeSeriesEditingSupport editingSupport=_viewer.getEditingSupport();
  if (editingSupport == null)   return;
  final TimeSeriesContentProvider cp=(TimeSeriesContentProvider)_viewer.getContentProvider();
  if (cp == null)   return;
  final double value=cp.getValue(cell.getElement(),computePeriodIndex(cell));
  final NumberFormat format=getEditingNumberFormat(editingSupport);
  cellEditor.setValue(format.format(value));
}
 

Example 26

From project jafka, under directory /src/main/java/com/sohu/jafka/log/.

Source file: Log.java

  18 
vote

/** 
 * Make log segment file name from offset bytes. All this does is pad out the offset number with zeros so that ls sorts the files numerically
 */
public static String nameFromOffset(long offset){
  NumberFormat nf=NumberFormat.getInstance();
  nf.setMinimumIntegerDigits(20);
  nf.setMaximumFractionDigits(0);
  nf.setGroupingUsed(false);
  return nf.format(offset) + Log.FileSuffix;
}
 

Example 27

From project jAPS2, under directory /src/com/agiletec/aps/system/common/entity/model/attribute/.

Source file: NumberAttribute.java

  18 
vote

/** 
 * Return the number in the format used for the current language, expressed in form of percentage. Using this method, a fractional number like. eg., 0.53 is displayed as 53%. 
 * @return The formatted number.
 */
public String getPercentNumber(){
  String number="";
  if (null != this.getNumber()) {
    NumberFormat numberInstance=NumberFormat.getPercentInstance(new Locale(getRenderingLang(),""));
    number=numberInstance.format(this.getNumber());
  }
  return number;
}
 

Example 28

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

Source file: Util.java

  18 
vote

public static String float2string(Float arg,Locale loc){
  if (arg == null) {
    return null;
  }
  NumberFormat nf=NumberFormat.getInstance(loc);
  return nf.format(arg);
}
 

Example 29

From project jspcompressor, under directory /src/jargs/gnu/.

Source file: CmdLineParser.java

  18 
vote

protected Object parseValue(String arg,Locale locale) throws IllegalOptionValueException {
  try {
    NumberFormat format=NumberFormat.getNumberInstance(locale);
    Number num=(Number)format.parse(arg);
    return new Double(num.doubleValue());
  }
 catch (  ParseException e) {
    throw new IllegalOptionValueException(this,arg);
  }
}
 

Example 30

From project jtrek, under directory /src/org/gamehost/jtrek/javatrek/.

Source file: TrekHud.java

  18 
vote

protected String getFormattedWarpSpeed(double warpSpeed){
  NumberFormat numformat;
  numformat=NumberFormat.getInstance();
  numformat.setMaximumFractionDigits(1);
  numformat.setMinimumFractionDigits(1);
  String formattedWarp=numformat.format(warpSpeed);
  return formattedWarp;
}
 

Example 31

From project log4j, under directory /tests/src/java/org/apache/log4j/.

Source file: TestLogMF.java

  18 
vote

/** 
 * Test LogMF.trace with single field pattern with float argument.
 */
public void testTraceFloat(){
  LogCapture capture=new LogCapture(TRACE);
  logger.setLevel(TRACE);
  float val=3.14f;
  NumberFormat format=NumberFormat.getInstance();
  LogMF.trace(logger,"Iteration {0}",val);
  assertEquals("Iteration " + format.format(val),capture.getMessage());
}
 

Example 32

From project log4jna, under directory /thirdparty/log4j/tests/src/java/org/apache/log4j/.

Source file: TestLogMF.java

  18 
vote

/** 
 * Test LogMF.trace with single field pattern with float argument.
 */
public void testTraceFloat(){
  LogCapture capture=new LogCapture(TRACE);
  logger.setLevel(TRACE);
  float val=3.14f;
  NumberFormat format=NumberFormat.getInstance();
  LogMF.trace(logger,"Iteration {0}",val);
  assertEquals("Iteration " + format.format(val),capture.getMessage());
}
 

Example 33

From project Archimedes, under directory /br.org.archimedes.core/src/br/org/archimedes/gui/swt/layers/.

Source file: LayerTable.java

  17 
vote

/** 
 * @param item The table item associated to this layer.
 * @param layer The layer containing the model.
 */
private void updateItem(TableItem item,Layer layer){
  Display display=shell.getDisplay();
  String oldName=item.getText(0);
  if (!oldName.equals(layer.getName())) {
    layers.remove(oldName);
    layers.put(layer.getName(),layer);
    item.setText(0,layer.getName());
  }
  item.setText(1,"" + layer.isVisible());
  item.setText(2,"" + layer.isLocked());
  item.setBackground(3,layer.getColor().toSWTColor(display));
  item.setForeground(3,layer.getColor().toSWTColor(display));
  item.setText(4,layer.getLineStyle().getName());
  NumberFormat nf=NumberFormat.getInstance(Locale.US);
  item.setText(5,nf.format(layer.getThickness()));
  item.setBackground(6,layer.getPrintColor().toSWTColor(display));
  item.setForeground(6,layer.getPrintColor().toSWTColor(display));
  item.setData(layer);
}
 

Example 34

From project com.idega.content, under directory /src/java/com/idega/content/upload/business/.

Source file: FileUploadProgressListenerBean.java

  17 
vote

@Override public String getFileUploadStatus(String id){
  if (!StringUtil.isEmpty(id) && failedUploads.contains(id)) {
    failedUploads.remove(id);
    LOGGER.warning("Upload by ID " + id + " has failed");
    return String.valueOf(-1);
  }
  if (fileSize <= 0) {
    LOGGER.warning("Invalid file size: " + fileSize);
    return null;
  }
  double progress=Long.valueOf(bytesTransferred).doubleValue() / Long.valueOf(fileSize).doubleValue();
  String hundredPercent=String.valueOf(100);
  if (bytesTransferred >= fileSize) {
    if (fileItemNumberInUploadSequence >= 0 && uploadedItemNr >= fileItemNumberInUploadSequence)     return hundredPercent;
    return hundredPercent;
  }
  if (progress >= 0.99)   return hundredPercent;
  NumberFormat nf=NumberFormat.getPercentInstance(Locale.ENGLISH);
  String status=nf.format(progress);
  return status.substring(0,status.length() - 1);
}
 

Example 35

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

Source file: Timers.java

  17 
vote

public void print(final Writer pw,final boolean shortForm,final String sortBy){
  String[] colNames=shortForm ? new String[]{"Name","Total (ms)"} : new String[]{"Name","Count","Avg","Total (ms)"};
  boolean[] alignment=shortForm ? new boolean[]{false,true} : new boolean[]{false,true,true,true};
  List<Timer> list=new ArrayList<Timer>(timers.values());
  if (sortBy != null) {
    Collections.sort(list,new Comparator<Timer>(){
      public int compare(      Timer o1,      Timer o2){
        if (sortBy.equalsIgnoreCase("Total")) {
          long t1=o1.getTotal();
          long t2=o2.getTotal();
          if (t1 == 0)           t1=o1.getElapsed();
          if (t2 == 0)           t2=o2.getElapsed();
          return (int)(t2 - t1);
        }
 else         if (sortBy.equalsIgnoreCase("Avg"))         return (int)(o2.getAverage() - o1.getAverage());
 else         if (sortBy.equalsIgnoreCase("Count"))         return (int)(o2.getCount() - o1.getCount());
 else         return AlphaNumericComparator.CASE_INSENSITIVE.compare(o1,o2);
      }
    }
);
  }
  NumberFormat nf=new DecimalFormat("0.00000");
  TableData table=new TableData(Arrays.asList(colNames));
  table.setAlignment(alignment);
  for (  Timer timer : list) {
    List<Object> row=new ArrayList<Object>();
    row.add(timer.getName());
    if (!shortForm) {
      row.add(String.valueOf(timer.getCount()));
      row.add(nf.format(timer.getAverage()));
    }
    row.add(String.valueOf(timer.getTotal() + timer.getElapsed()));
    table.add(row);
  }
  table.print(pw);
}
 

Example 36

From project crammer, under directory /src/main/java/org/apache/commons/math/stat/.

Source file: HashMapFrequency.java

  17 
vote

/** 
 * Return a string representation of this frequency distribution.
 * @return a string representation.
 */
@Override public String toString(){
  NumberFormat nf=NumberFormat.getPercentInstance();
  StringBuilder outBuffer=new StringBuilder();
  outBuffer.append("Value \t Freq. \t Pct. \t Cum Pct. \n");
  Iterator<Comparable<?>> iter=freqTable.keySet().iterator();
  Comparable<?>[] array=new Comparable<?>[freqTable.size()];
  int i=0;
  while (iter.hasNext()) {
    array[i++]=iter.next();
  }
  Arrays.sort(array);
  double cumPct=0;
  final long sumFreq=getSumFreq();
  for (i=0; i < array.length; i++) {
    Comparable<?> value=array[i];
    long count=getCount(value);
    double pct=sumFreq == 0 ? Double.NaN : (double)count / (double)sumFreq;
    cumPct+=pct;
    outBuffer.append(value);
    outBuffer.append('\t');
    outBuffer.append(count);
    outBuffer.append('\t');
    outBuffer.append(nf.format(pct));
    outBuffer.append('\t');
    outBuffer.append(nf.format(cumPct));
    outBuffer.append('\n');
  }
  return outBuffer.toString();
}
 

Example 37

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

Source file: FileInfo.java

  17 
vote

public static String getSizeStr(long size){
  String str;
  if (size > GB) {
    NumberFormat fmt=new DecimalFormat("#.##GB");
    str=fmt.format((double)size / GB);
  }
 else   if (size > MB) {
    NumberFormat fmt=new DecimalFormat("#.#MB");
    str=fmt.format((double)size / MB);
  }
 else {
    NumberFormat fmt=new DecimalFormat("#KB");
    str=fmt.format((double)size / KB);
  }
  return str;
}
 

Example 38

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/io/.

Source file: FileUtils.java

  17 
vote

/** 
 * Formats a file size
 * @param longSize
 * @param decimalPos
 * @return formatted string for size.
 */
public static String formatSize(long longSize,int decimalPos){
  NumberFormat fmt=NumberFormat.getNumberInstance();
  if (decimalPos >= 0) {
    fmt.setMaximumFractionDigits(decimalPos);
  }
  final double size=longSize;
  double val=size / (1024 * 1024 * 1024);
  if (val > 1) {
    return fmt.format(val).concat(" GB");
  }
  val=size / (1024 * 1024);
  if (val > 1) {
    return fmt.format(val).concat(" MB");
  }
  val=size / 1024;
  if (val > 10) {
    return fmt.format(val).concat(" KB");
  }
  return fmt.format(size).concat(" bytes");
}
 

Example 39

From project dawn-isenciaui, under directory /com.isencia.passerelle.workbench.model.ui/src/main/java/com/isencia/passerelle/workbench/model/ui/utils/.

Source file: FileUtils.java

  17 
vote

/** 
 * Formats a file size
 * @param longSize
 * @param decimalPos
 * @return formatted string for size.
 */
public static String formatSize(long longSize,int decimalPos){
  NumberFormat fmt=NumberFormat.getNumberInstance();
  if (decimalPos >= 0) {
    fmt.setMaximumFractionDigits(decimalPos);
  }
  final double size=longSize;
  double val=size / (1024 * 1024 * 1024);
  if (val > 1) {
    return fmt.format(val).concat(" GB");
  }
  val=size / (1024 * 1024);
  if (val > 1) {
    return fmt.format(val).concat(" MB");
  }
  val=size / 1024;
  if (val > 10) {
    return fmt.format(val).concat(" KB");
  }
  return fmt.format(size).concat(" bytes");
}
 

Example 40

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

Source file: TraceConfigPage.java

  17 
vote

protected void exportToCSV(IFile exportTo,IDataProvider dataProvider) throws Exception {
  final IFile csv=getUniqueFile(exportTo,null,"csv");
  final StringBuilder contents=new StringBuilder();
  final IDataProvider prov=trace.getDataProvider();
  final NumberFormat format=new DecimalFormat("##0.#####E0");
  for (int i=0; i < prov.getSize(); i++) {
    final ISample isample=prov.getSample(i);
    contents.append(format.format(isample.getXValue()));
    contents.append(",\t");
    contents.append(format.format(isample.getYValue()));
    contents.append("\n");
  }
  InputStream stream=new ByteArrayInputStream(contents.toString().getBytes());
  csv.create(stream,true,new NullProgressMonitor());
  csv.getParent().refreshLocal(IResource.DEPTH_INFINITE,new NullProgressMonitor());
  final IWorkbenchPage page=PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
  IEditorDescriptor desc=PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(csv.getName());
  if (desc == null)   desc=PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(csv.getName() + ".txt");
  page.openEditor(new FileEditorInput(csv),desc.getId());
}
 

Example 41

From project empire-db, under directory /empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/.

Source file: TextInputControl.java

  17 
vote

@Override protected Object parseInputValue(String value,InputInfo ii){
  if (hasFormatOption(ii,"notrim") == false)   value=value.trim();
  Column column=ii.getColumn();
  DataType type=column.getDataType();
  if (type.isText())   return value;
  if (type == DataType.INTEGER) {
    NumberFormat nf=NumberFormat.getIntegerInstance(ii.getLocale());
    return parseNumber(value,nf);
  }
  if (type == DataType.DECIMAL || type == DataType.FLOAT) {
    NumberFormat nf=NumberFormat.getNumberInstance(ii.getLocale());
    return parseNumber(value,nf);
  }
  if (type == DataType.DATE || type == DataType.DATETIME) {
    return parseDate(value,getDateFormat(column.getDataType(),ii,column));
  }
  if (type == DataType.BOOL) {
    return ObjectUtils.getBoolean(value);
  }
  if (type == DataType.AUTOINC) {
    log.error("Autoinc-value cannot be changed.");
    return null;
  }
  return value;
}
 

Example 42

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

Source file: CrossValidateSunspot.java

  17 
vote

public void predict(BasicNetwork network){
  NumberFormat f=NumberFormat.getNumberInstance();
  f.setMaximumFractionDigits(4);
  f.setMinimumFractionDigits(4);
  System.out.println("Year\tActual\tPredict\tClosed Loop Predict");
  for (int year=EVALUATE_START; year < EVALUATE_END; year++) {
    MLData input=new BasicMLData(WINDOW_SIZE);
    for (int i=0; i < input.size(); i++) {
      input.setData(i,this.normalizedSunspots[(year - WINDOW_SIZE) + i]);
    }
    MLData output=network.compute(input);
    double prediction=output.getData(0);
    this.closedLoopSunspots[year]=prediction;
    for (int i=0; i < input.size(); i++) {
      input.setData(i,this.closedLoopSunspots[(year - WINDOW_SIZE) + i]);
    }
    output=network.compute(input);
    double closedLoopPrediction=output.getData(0);
    System.out.println((STARTING_YEAR + year) + "\t" + f.format(this.normalizedSunspots[year])+ "\t"+ f.format(prediction)+ "\t"+ f.format(closedLoopPrediction));
  }
}
 

Example 43

From project gda-common, under directory /uk.ac.gda.common/src/uk/ac/gda/util/io/.

Source file: FileUtils.java

  17 
vote

/** 
 * Formats a file size
 * @param longSize
 * @param decimalPos
 * @return formatted string for size.
 */
public static String formatSize(long longSize,int decimalPos){
  NumberFormat fmt=NumberFormat.getNumberInstance();
  if (decimalPos >= 0) {
    fmt.setMaximumFractionDigits(decimalPos);
  }
  final double size=longSize;
  double val=size / (1024 * 1024 * 1024);
  if (val > 1) {
    return fmt.format(val).concat(" GB");
  }
  val=size / (1024 * 1024);
  if (val > 1) {
    return fmt.format(val).concat(" MB");
  }
  val=size / 1024;
  if (val > 10) {
    return fmt.format(val).concat(" KB");
  }
  return fmt.format(size).concat(" bytes");
}
 

Example 44

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

Source file: StringUtils.java

  17 
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 45

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

Source file: GpsLoggingService.java

  17 
vote

/** 
 * Shows a notification icon in the status bar for GPS Logger
 */
private void ShowNotification(){
  Utilities.LogDebug("GpsLoggingService.ShowNotification");
  Intent contentIntent=new Intent(this,GpsMainActivity.class);
  PendingIntent pending=PendingIntent.getActivity(getApplicationContext(),0,contentIntent,android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
  Notification nfc=new Notification(R.drawable.gpsloggericon2,null,System.currentTimeMillis());
  nfc.flags|=Notification.FLAG_ONGOING_EVENT;
  NumberFormat nf=new DecimalFormat("###.######");
  String contentText=getString(R.string.gpslogger_still_running);
  if (Session.hasValidLocation()) {
    contentText=nf.format(Session.getCurrentLatitude()) + "," + nf.format(Session.getCurrentLongitude());
  }
  nfc.setLatestEventInfo(getApplicationContext(),getString(R.string.gpslogger_still_running),contentText,pending);
  gpsNotifyManager.notify(NOTIFICATION_ID,nfc);
  Session.setNotificationVisible(true);
}
 

Example 46

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

Source file: Metric.java

  17 
vote

/** 
 * Format value as a difference to out.  Values greater than 1.0 will be formatted as a multiple (ex: 1.1 --&gt; "2.100x"). Note that 1.0 is added to the difference in this case. Consider an initial value 1.0 and final value 2.1. The difference is computed as (final - initial) / initial = 1.1 and thus formatted as "2.100x".  All other values (&lt;= 1.0) will be formatted as a positive or negative percentage: (ex: 0.25 --&gt; "+25.0%").  Values will be left padded as necessary for output to six character width. Values outside the range (-9.995, 9998.5) will be formatted using more than six characters.
 */
public static void formatDifference(double value,StringBuilder out){
  if (Double.isNaN(value)) {
    out.append("   N/A");
    return;
  }
  double r=value;
  char symbol;
  int fdigits=3;
  if (r > 1.0d) {
    r+=1.0d;
    if (r >= 999.95)     fdigits=0;
 else     if (r >= 99.995)     fdigits=1;
 else     if (r >= 9.995)     fdigits=2;
    symbol='x';
  }
 else {
    r*=100d;
    if (r >= 99.995)     fdigits=0;
 else     if (r >= 9.995)     fdigits=1;
 else     if (r <= -99.95)     fdigits=0;
 else     if (r <= -9.995)     fdigits=1;
 else     fdigits=2;
    symbol='%';
  }
  NumberFormat f=NumberFormat.getNumberInstance();
  f.setMinimumFractionDigits(fdigits);
  f.setMaximumFractionDigits(fdigits);
  f.setGroupingUsed(true);
  if (r > 0d && symbol == '%')   out.append('+');
  String vf=f.format(r);
  int flen=vf.length();
  while (out.length() < (5 - flen))   out.append(' ');
  out.append(vf);
  out.append(symbol);
}
 

Example 47

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

Source file: GenericUDFToNumber.java

  17 
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 48

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

Source file: NumberConverter.java

  17 
vote

/** 
 * @throws ConverterException   {@inheritDoc}
 * @throws NullPointerException {@inheritDoc}
 */
public String getAsString(FacesContext context,UIComponent component,Object value){
  if (context == null || component == null) {
    throw new NullPointerException();
  }
  try {
    if (value == null) {
      return "";
    }
    if (value instanceof String) {
      return (String)value;
    }
    Locale locale=getLocale(context);
    NumberFormat formatter=getNumberFormat(locale);
    if (((pattern != null) && pattern.length() != 0) || "currency".equals(type)) {
      configureCurrency(formatter);
    }
    configureFormatter(formatter);
    return (formatter.format(value));
  }
 catch (  ConverterException e) {
    throw new ConverterException(MessageFactory.getMessage(context,STRING_ID,value,MessageFactory.getLabel(context,component)),e);
  }
catch (  Exception e) {
    throw new ConverterException(MessageFactory.getMessage(context,STRING_ID,value,MessageFactory.getLabel(context,component)),e);
  }
}
 

Example 49

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

Source file: FormatNumberSupport.java

  17 
vote

private NumberFormat createFormatter(Locale loc) throws JspException {
  NumberFormat formatter=null;
  if ((type == null) || NUMBER.equalsIgnoreCase(type)) {
    formatter=NumberFormat.getNumberInstance(loc);
  }
 else   if (CURRENCY.equalsIgnoreCase(type)) {
    formatter=NumberFormat.getCurrencyInstance(loc);
  }
 else   if (PERCENT.equalsIgnoreCase(type)) {
    formatter=NumberFormat.getPercentInstance(loc);
  }
 else {
    throw new JspException(Resources.getMessage("FORMAT_NUMBER_INVALID_TYPE",type));
  }
  return formatter;
}
 

Example 50

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

Source file: MoneyAmountStyle.java

  17 
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 51

From project lastfm-android, under directory /app/src/fm/last/android/activity/.

Source file: Metadata.java

  17 
vote

@Override public Boolean doInBackground(Void... params){
  Artist artist;
  boolean success=false;
  try {
    String lang=Locale.getDefault().getLanguage();
    if (lang.equalsIgnoreCase("de")) {
      artist=mServer.getArtistInfo(mArtistName,null,lang);
    }
 else {
      artist=mServer.getArtistInfo(mArtistName,null,null);
    }
    if (artist.getBio().getContent() == null || artist.getBio().getContent().trim().length() == 0) {
      artist=mServer.getArtistInfo(mArtistName,null,null);
    }
    String imageURL="";
    for (    ImageUrl image : artist.getImages()) {
      if (image.getSize().contentEquals("large")) {
        imageURL=image.getUrl();
        break;
      }
    }
    String listeners="";
    String plays="";
    try {
      NumberFormat nf=NumberFormat.getInstance();
      listeners=nf.format(Integer.parseInt(artist.getListeners()));
      plays=nf.format(Integer.parseInt(artist.getPlaycount()));
    }
 catch (    NumberFormatException e) {
    }
    mBio="<html><body style='margin:0; padding:0; color:black; background: white; font-family: Helvetica; font-size: 11pt;'>" + "<div style='padding:17px; margin:0; top:0px; left:0px; position:absolute;'>" + "<img src='" + imageURL + "' style='margin-top: 4px; float: left; margin-right: 0px; margin-bottom: 14px; width:64px; border:1px solid gray; padding: 1px;'/>"+ "<div style='margin-left:84px; margin-top:3px'>"+ "<span style='font-size: 15pt; font-weight:bold; padding:0px; margin:0px;'>"+ mArtistName+ "</span><br/>"+ "<span style='color:gray; font-weight: normal; font-size: 10pt;'>"+ listeners+ " "+ getString(R.string.metadata_listeners)+ "<br/>"+ plays+ " "+ getString(R.string.metadata_plays)+ "</span></div>"+ "<br style='clear:both;'/>"+ formatBio(artist.getBio().getContent())+ "</div></body></html>";
    success=true;
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return success;
}
 

Example 52

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

Source file: StringUtils.java

  17 
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 53

From project litle-sdk-for-java, under directory /lib/jaxb/samples/ubl/src/samples/ubl/report/.

Source file: PrintOrder.java

  17 
vote

/** 
 * Prints information about line items in this order, including extension based on quantity and base price and a total of all extensions.
 * @param order a UBL <code>Order</code>
 */
private static void printLineItems(OrderFacade order){
  double total=0;
  NumberFormat form=NumberFormat.getCurrencyInstance();
  java.util.Iterator iter=order.getLineItemIter();
  for (int i=0; iter.hasNext(); i++) {
    OrderLineTypeFacade lineItem=(OrderLineTypeFacade)iter.next();
    double price=lineItem.getItemPrice();
    int qty=lineItem.getItemQuantity();
    double subtotal=qty * price;
    total+=subtotal;
    form.setCurrency(lineItem.getItemPriceCurrency());
    System.out.println("\n" + (i + 1) + ". Part No.: "+ lineItem.getItemPartNumber()+ "\n   Description: "+ lineItem.getItemDescription()+ "\n   Price: "+ form.format(price)+ "\n   Qty.: "+ qty+ "\n   Subtotal: "+ form.format(subtotal));
  }
  System.out.println("\nTotal: " + form.format(total));
}
 

Example 54

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

Source file: SynchronizeLogResourceHandler.java

  17 
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 55

From project mache, under directory /src/com/streak/logging/analysis/.

Source file: AnalysisUtility.java

  17 
vote

public static String formatCsvValue(Object fieldValue,String type){
  NumberFormat nf=createFixedPointFormat();
  if ("string" == type) {
    if (fieldValue instanceof Text) {
      return AnalysisUtility.escapeAndQuoteField(((Text)fieldValue).getValue());
    }
    return AnalysisUtility.escapeAndQuoteField("" + fieldValue);
  }
  if ("float" == type) {
    return nf.format(fieldValue);
  }
  if ("integer" == type) {
    if (fieldValue instanceof Date) {
      return "" + ((Date)fieldValue).getTime();
    }
  }
  return "" + fieldValue;
}
 

Example 56

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/validation/.

Source file: NumericValidator.java

  15 
vote

public void validate(Model m){
  Object value=m.get(attribute);
  if (!present(value,m)) {
    return;
  }
  if (convertNullIfEmpty && "".equals(value)) {
    m.set(attribute,null);
    value=null;
  }
  if (value == null && allowNull) {
    return;
  }
  if (value != null) {
    try {
      ParsePosition pp=new ParsePosition(0);
      String input=value.toString();
      NumberFormat.getInstance().parse(input,pp);
      if (pp.getIndex() != (input.length()))       throw new RuntimeException("");
    }
 catch (    Exception e) {
      m.addValidator(this,attribute);
    }
  }
 else {
    m.addValidator(this,attribute);
  }
  if (min != null) {
    validateMin(Convert.toDouble(value),m);
  }
  if (max != null) {
    validateMax(Convert.toDouble(value),m);
  }
  if (onlyInteger) {
    validateIntegerOnly(value,m);
  }
}
 

Example 57

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

Source file: AuxComponentFactory.java

  15 
vote

public static JTextField createNonNegativeIntegerTextField(ValueModel model){
  NumberFormatter numberFormatter=new EmptyNumberFormatter(NumberFormat.getIntegerInstance(),0);
  numberFormatter.setValueClass(Integer.class);
  numberFormatter.setMinimum(0);
  JFormattedTextField field=new JFormattedTextField(numberFormatter);
  field.setColumns(3);
  Bindings.bind(field,model);
  return field;
}
 

Example 58

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/io/file/.

Source file: FileScan.java

  15 
vote

private void report(final int depth){
  this.report.println(depth,"Files: " + NumberFormat.getInstance().format(getFiles()));
  this.report.println(depth,"Directories: " + NumberFormat.getInstance().format(getDirectories()));
  this.report.println(depth,"Empty Directories: " + NumberFormat.getInstance().format(getEmptyDirectories()));
  this.report.println(depth,"Bytes: " + NumberFormat.getInstance().format(getBytes()));
  this.report.println(depth,"Size: " + DataSizeUnit.format(getBytes()));
  this.report.rule();
  for (int range=0; range < ranges.length - 1; range++) {
    this.report.println(depth,DataSizeUnit.format(ranges[range]) + " to " + DataSizeUnit.format(ranges[range + 1]));
    this.report.println(depth + 1,"Files: " + NumberFormat.getInstance().format(rangeCountSizes[range][0]));
    this.report.println(depth + 1,"Size: " + DataSizeUnit.format(rangeCountSizes[range][1]));
  }
}
 

Example 59

From project Arecibo, under directory /dashboard/src/main/java/com/ning/arecibo/dashboard/format/.

Source file: BitsFormatter.java

  15 
vote

public static NumberFormat getNumberFormatInstance(String formatSpecifier,int numDecimals){
  NumberFormat[] formatInstances;
  if (formatSpecifier == null || formatSpecifier.equals(FORMAT_TYPE_BITS_OCTETS))   formatInstances=numberFormatBitsOctetsInstances;
 else   formatInstances=numberFormatBitsOctetsInstances;
  if (numDecimals >= 0 && numDecimals < formatInstances.length)   return formatInstances[numDecimals];
  return formatInstances[0];
}
 

Example 60

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/filesearch/.

Source file: SizeSearchPanel.java

  15 
vote

/** 
 * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked") private void initComponents(){
  rightClickMenu=new javax.swing.JPopupMenu();
  cutMenuItem=new javax.swing.JMenuItem();
  copyMenuItem=new javax.swing.JMenuItem();
  pasteMenuItem=new javax.swing.JMenuItem();
  selectAllMenuItem=new javax.swing.JMenuItem();
  sizeUnitComboBox=new javax.swing.JComboBox();
  sizeTextField=new JFormattedTextField(NumberFormat.getIntegerInstance());
  sizeCompareComboBox=new javax.swing.JComboBox();
  sizeCheckBox=new javax.swing.JCheckBox();
  cutMenuItem.setText(org.openide.util.NbBundle.getMessage(SizeSearchPanel.class,"SizeSearchPanel.cutMenuItem.text"));
  rightClickMenu.add(cutMenuItem);
  copyMenuItem.setText(org.openide.util.NbBundle.getMessage(SizeSearchPanel.class,"SizeSearchPanel.copyMenuItem.text"));
  rightClickMenu.add(copyMenuItem);
  pasteMenuItem.setText(org.openide.util.NbBundle.getMessage(SizeSearchPanel.class,"SizeSearchPanel.pasteMenuItem.text"));
  rightClickMenu.add(pasteMenuItem);
  selectAllMenuItem.setText(org.openide.util.NbBundle.getMessage(SizeSearchPanel.class,"SizeSearchPanel.selectAllMenuItem.text"));
  rightClickMenu.add(selectAllMenuItem);
  sizeUnitComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Byte(s)","KB","MB","GB","TB"}));
  sizeTextField.setValue(0);
  sizeTextField.addMouseListener(new java.awt.event.MouseAdapter(){
    public void mouseClicked(    java.awt.event.MouseEvent evt){
      sizeTextFieldMouseClicked(evt);
    }
  }
);
  sizeCompareComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"equal to","greater than","less than"}));
  sizeCheckBox.setText(org.openide.util.NbBundle.getMessage(SizeSearchPanel.class,"SizeSearchPanel.sizeCheckBox.text"));
  javax.swing.GroupLayout layout=new javax.swing.GroupLayout(this);
  this.setLayout(layout);
  layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(sizeCheckBox).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(sizeCompareComboBox,javax.swing.GroupLayout.PREFERRED_SIZE,95,javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(sizeTextField,javax.swing.GroupLayout.PREFERRED_SIZE,79,javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(sizeUnitComboBox,javax.swing.GroupLayout.PREFERRED_SIZE,72,javax.swing.GroupLayout.PREFERRED_SIZE)));
  layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(sizeCompareComboBox,javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(sizeTextField,javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(sizeUnitComboBox,javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(sizeCheckBox)));
}
 

Example 61

From project aviator, under directory /src/test/java/com/googlecode/aviator/.

Source file: SimpleELPerformanceTest.java

  15 
vote

private void perf(Map<String,Object> ctx){
  Expression exp=AviatorEvaluator.compile("(a+b)*c");
  long startMillis=System.currentTimeMillis();
  final int COUNT=1000 * 1000;
  for (int i=0; i < COUNT; ++i) {
    exp.execute(ctx);
  }
  long millis=System.currentTimeMillis() - startMillis;
  System.out.println("time : " + NumberFormat.getInstance().format(millis));
}
 

Example 62

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/rcputils/de/ralfebert/rcputils/tables/format/.

Source file: Formatter.java

  15 
vote

/** 
 * Returns a formatter for String to double/Double by NumberFormat
 */
public static StringValueFormatter forDouble(NumberFormat numberFormat){
  return new StringValueFormatter(numberFormat){
    @Override public Object parse(    String str){
      return ((Number)super.parse(str)).doubleValue();
    }
  }
;
}
 

Example 63

From project Binaural-Beats, under directory /src/com/jjoe64/graphview/.

Source file: GraphView.java

  15 
vote

/** 
 * formats the label can be overwritten
 * @param value x and y values
 * @param isValueX if false, value y wants to be formatted
 * @return value to display
 */
protected String formatLabel(double value,boolean isValueX){
  if (numberformatter == null) {
    numberformatter=NumberFormat.getNumberInstance();
    double highestvalue=getMaxY();
    double lowestvalue=getMinY();
    if (highestvalue - lowestvalue < 0.1) {
      numberformatter.setMaximumFractionDigits(6);
    }
 else     if (highestvalue - lowestvalue < 1) {
      numberformatter.setMaximumFractionDigits(4);
    }
 else     if (highestvalue - lowestvalue < 20) {
      numberformatter.setMaximumFractionDigits(3);
    }
 else     if (highestvalue - lowestvalue < 100) {
      numberformatter.setMaximumFractionDigits(1);
    }
 else {
      numberformatter.setMaximumFractionDigits(0);
    }
  }
  return numberformatter.format(value);
}
 

Example 64

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

Source file: Matrix.java

  15 
vote

/** 
 * Print the matrix to the output stream. Line the elements up in columns. Use the format object, and right justify within columns of width characters. Note that is the matrix is to be read back in, you probably will want to use a NumberFormat that is set to US Locale.
 * @param output the output stream.
 * @param format A formatting object to format the matrix elements
 * @param width Column width.
 * @see java.text.DecimalFormat#setDecimalFormatSymbols
 */
public void print(PrintWriter output,NumberFormat format,int width){
  output.println();
  for (int i=0; i < m; i++) {
    for (int j=0; j < n; j++) {
      String s=format.format(A[i][j]);
      int padding=Math.max(1,width - s.length());
      for (int k=0; k < padding; k++)       output.print(' ');
      output.print(s);
    }
    output.println();
  }
  output.println();
}
 

Example 65

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

Source file: NumberFormatRenderer.java

  15 
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 66

From project collections-generic, under directory /src/java/org/apache/commons/collections15/.

Source file: MapUtils.java

  15 
vote

/** 
 * Gets a Number from a Map in a null-safe manner. <p/> If the value is a <code>Number</code> it is returned directly. If the value is a <code>String</code> it is converted using {@link NumberFormat#parse(String)} on the system default formatterreturning <code>null</code> if the conversion fails. Otherwise, <code>null</code> is returned.
 * @param map the map to use
 * @param key the key to look up
 * @return the value in the Map as a Number, <code>null</code> if null map input
 */
public static Number getNumber(final Map map,final Object key){
  if (map != null) {
    Object answer=map.get(key);
    if (answer != null) {
      if (answer instanceof Number) {
        return (Number)answer;
      }
 else       if (answer instanceof String) {
        try {
          String text=(String)answer;
          return NumberFormat.getInstance().parse(text);
        }
 catch (        ParseException e) {
          logInfo(e);
        }
      }
    }
  }
  return null;
}
 

Example 67

From project cpptasks-parallel, under directory /src/main/java/net/sf/antcontrib/cpptasks/apple/.

Source file: XcodeProjectWriter.java

  15 
vote

/** 
 * Create PBXFrameworksBuildPhase.
 * @param buildActionMask build action mask.
 * @param files files.
 * @param runOnly if true, phase should only be run on deployment.
 * @return PBXFrameworkBuildPhase.
 */
private static PBXObjectRef createPBXFrameworksBuildPhase(final int buildActionMask,final List files,final boolean runOnly){
  Map map=new HashMap();
  map.put("isa","PBXFrameworksBuildPhase");
  map.put("buildActionMask",NumberFormat.getIntegerInstance(Locale.US).format(buildActionMask));
  map.put("files",files);
  map.put("runOnlyForDeploymentPostprocessing",toString(runOnly));
  return new PBXObjectRef(map);
}
 

Example 68

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

Source file: BenchmarkReport.java

  15 
vote

private void writeBestScoreSummaryCharts(){
  List<DefaultCategoryDataset> datasetList=new ArrayList<DefaultCategoryDataset>(CHARTED_SCORE_LEVEL_SIZE);
  for (  SolverBenchmark solverBenchmark : plannerBenchmark.getSolverBenchmarkList()) {
    String solverLabel=solverBenchmark.getNameWithFavoriteSuffix();
    for (    SingleBenchmark singleBenchmark : solverBenchmark.getSingleBenchmarkList()) {
      String planningProblemLabel=singleBenchmark.getProblemBenchmark().getName();
      if (singleBenchmark.isSuccess()) {
        double[] levelValues=singleBenchmark.getScore().toDoubleLevels();
        for (int i=0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) {
          if (i >= datasetList.size()) {
            datasetList.add(new DefaultCategoryDataset());
          }
          datasetList.get(i).addValue(levelValues[i],solverLabel,planningProblemLabel);
        }
      }
    }
  }
  bestScoreSummaryChartFileList=new ArrayList<File>(datasetList.size());
  int scoreLevelIndex=0;
  for (  DefaultCategoryDataset dataset : datasetList) {
    CategoryPlot plot=createBarChartPlot(dataset,"Score level " + scoreLevelIndex,NumberFormat.getInstance(locale));
    JFreeChart chart=new JFreeChart("Best score level " + scoreLevelIndex + " summary (higher is better)",JFreeChart.DEFAULT_TITLE_FONT,plot,true);
    bestScoreSummaryChartFileList.add(writeChartToImageFile(chart,"bestScoreSummaryLevel" + scoreLevelIndex));
    scoreLevelIndex++;
  }
}
 

Example 69

From project Eclipse, under directory /com.mobilesorcery.sdk.testing/src/com/mobilesorcery/sdk/testing/internal/ui/.

Source file: TestSessionLabelProvider.java

  15 
vote

public TestSessionLabelProvider(){
  timeFormat=NumberFormat.getNumberInstance();
  timeFormat.setGroupingUsed(true);
  timeFormat.setMinimumFractionDigits(3);
  timeFormat.setMaximumFractionDigits(3);
  timeFormat.setMinimumIntegerDigits(1);
}
 

Example 70

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

Source file: LenientFormatter.java

  15 
vote

private NumberFormat getNumberFormat(){
  if (null == numberFormat) {
    numberFormat=NumberFormat.getInstance(locale);
  }
  return numberFormat;
}
 

Example 71

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

Source file: FiggoI18nResponseInterceptor.java

  15 
vote

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

Example 72

From project gda-common-rcp, under directory /uk.ac.gda.common.rcp/src/uk/ac/gda/richbeans/components/scalebox/.

Source file: NumberBox.java

  15 
vote

public NumberBox(Composite parent,int style){
  super(parent,style);
  final GridLayout gridLayout=new GridLayout(3,false);
  gridLayout.verticalSpacing=0;
  gridLayout.marginWidth=0;
  gridLayout.marginHeight=0;
  gridLayout.horizontalSpacing=0;
  setLayout(gridLayout);
  this.label=new Label(this,SWT.LEFT);
  this.label.setLayoutData(new GridData(SWT.FILL,SWT.CENTER,false,false));
  label.setVisible(false);
  this.text=new StyledText(this,SWT.BORDER | SWT.SINGLE);
  this.text.setLayoutData(new GridData(SWT.FILL,SWT.CENTER,true,false));
  createTextListeners(text);
  text.setToolTipText(null);
  text.setStyleRange(null);
  this.mouseTrackListener=new MouseTrackAdapter(){
    @Override public void mouseEnter(    MouseEvent e){
      setupToolTip();
    }
    @Override public void mouseExit(    MouseEvent e){
      text.setToolTipText(null);
    }
  }
;
  text.addMouseTrackListener(mouseTrackListener);
  this.numberFormat=NumberFormat.getInstance();
  numberFormat.setMaximumFractionDigits(decimalPlaces);
  numberFormat.setMinimumFractionDigits(decimalPlaces);
  numberFormat.setGroupingUsed(false);
}
 

Example 73

From project genobyte, under directory /genobyte-simulation/src/main/java/ca/mcgill/genome/bitwise/simulation/.

Source file: BitwiseSimulation.java

  15 
vote

private void printProgress(int done,int todo){
  if (pct == null) {
    pct=NumberFormat.getPercentInstance();
    pct.setMinimumFractionDigits(2);
    pct.setMaximumFractionDigits(2);
  }
  double p=(done / (double)todo);
  System.out.print("\r" + pct.format(p) + " ("+ done+ ")");
}
 

Example 74

From project GradeCalculator-Android, under directory /GradeCalculator/src/com/jetheis/android/grades/listadapter/.

Source file: CourseArrayAdapter.java

  15 
vote

@Override public View getView(int position,View convertView,ViewGroup parent){
  View result=convertView;
  if (result == null) {
    LayoutInflater inflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    result=inflater.inflate(R.layout.course_list_line_item,null);
  }
  final Course currentCourse=getItem(position);
  TextView nameTextView=(TextView)result.findViewById(R.id.course_list_line_item_name_text_view);
  nameTextView.setText(currentCourse.getName());
  TextView gradeTextView=(TextView)result.findViewById(R.id.course_list_line_item_grade_text_view);
  gradeTextView.setText(NumberFormat.getPercentInstance().format(currentCourse.getOverallScore()));
  return result;
}
 

Example 75

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

Source file: RoundedFormattedTextField.java

  15 
vote

public RoundedFormattedTextField(NumberFormat format,Color backgroundColor,Color foregroundColor){
  super(format);
  this.backgroundColor=backgroundColor;
  setSelectedTextColor(UIHelper.BG_COLOR);
  setSelectionColor(UIHelper.LIGHT_GREEN_COLOR);
  setForeground(foregroundColor);
  setOpaque(false);
  setBorder(new EmptyBorder(3,5,3,5));
}
 

Example 76

From project Ivory_1, under directory /src/java/main/ivory/lsh/eval/.

Source file: BruteForcePwsim.java

  15 
vote

public void configure(JobConf conf){
  sLogger.setLevel(Level.INFO);
  numResults=conf.getInt("Ivory.NumResults",Integer.MAX_VALUE);
  nf=NumberFormat.getInstance();
  nf.setMaximumFractionDigits(3);
  nf.setMinimumFractionDigits(3);
}
 

Example 77

From project jftp, under directory /src/main/java/com/myjavaworld/jftp/.

Source file: RemoteFilePropertiesDlg.java

  15 
vote

private void populateScreen(){
  tfFileName.setText(file.getName());
  tfSite.setText(client.getRemoteHost());
  tfFullPath.setText(file.getPath());
  tfType.setText(file.getType());
  String size=sizeFormatter.format(new Long[]{new Long(file.getSize())});
  tfSize.setText(size);
  DateFormat df=DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.MEDIUM);
  Date lastModified=new Date(file.getLastModified());
  tfLastModified.setText(df.format(lastModified));
  String linkCount=NumberFormat.getInstance().format(file.getLinkCount());
  tfLinkCount.setText(linkCount);
  tfOwner.setText(file.getOwner());
  tfGroup.setText(file.getGroup());
}
 

Example 78

From project jira-hudson-integration, under directory /jira-hudson-plugin/src/main/java/com/marvelution/jira/plugins/hudson/charts/utils/.

Source file: DurationFormat.java

  15 
vote

/** 
 * Constructor
 * @param dayFormat the {@link NumberFormat} to use for the days
 * @param hourFormat the {@link NumberFormat} to use for the hours
 * @param minuteFormat the {@link NumberFormat} to use for the minutes
 * @param secondFormat the {@link NumberFormat} to use for the seconds
 */
public DurationFormat(NumberFormat dayFormat,NumberFormat hourFormat,NumberFormat minuteFormat,NumberFormat secondFormat){
  this.dayFormat=dayFormat;
  this.hourFormat=hourFormat;
  this.minuteFormat=minuteFormat;
  this.secondFormat=secondFormat;
}
 

Example 79

From project jira-rest-java-client, under directory /atlassian-jira-rest-java-client/src/test/java/it/.

Source file: JerseyIssueRestClientTest.java

  15 
vote

@Test public void testTransitionWithNumericCustomFieldPolishLocale() throws Exception {
  final double newValue=123.45;
  final FieldInput fieldInput;
  if (IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER) {
    fieldInput=new FieldInput(NUMERIC_CUSTOMFIELD_ID,Double.valueOf(newValue));
  }
 else {
    fieldInput=new FieldInput(NUMERIC_CUSTOMFIELD_ID,NumberFormat.getNumberInstance(new Locale("pl")).format(newValue));
  }
  assertTransitionWithNumericCustomField(fieldInput,newValue);
}
 

Example 80

From project jopt-simple, under directory /src/test/java/joptsimple/util/.

Source file: DateConverterTest.java

  15 
vote

@Before public void setUp(){
  notASimpleDateFormat=new DateFormat(){
    private static final long serialVersionUID=-1L;
{
      setNumberFormat(NumberFormat.getInstance());
    }
    @Override public StringBuffer format(    Date date,    StringBuffer toAppendTo,    FieldPosition fieldPosition){
      return null;
    }
    @Override public Date parse(    String source,    ParsePosition pos){
      return null;
    }
  }
;
  monthDayYear=new SimpleDateFormat("MM/dd/yyyy");
}
 

Example 81

From project jspwiki, under directory /src/org/apache/wiki/diff/.

Source file: TraditionalDiffProvider.java

  15 
vote

private void print(Chunk changed,String type){
  m_result.append(CSS_DIFF_UNCHANGED);
  String[] choiceString={m_rb.getString("diff.traditional.oneline"),m_rb.getString("diff.traditional.lines")};
  double[] choiceLimits={1,2};
  MessageFormat fmt=new MessageFormat("");
  fmt.setLocale(WikiContext.getLocale(m_context));
  ChoiceFormat cfmt=new ChoiceFormat(choiceLimits,choiceString);
  fmt.applyPattern(type);
  Format[] formats={NumberFormat.getInstance(),cfmt,NumberFormat.getInstance()};
  fmt.setFormats(formats);
  Object[] params={changed.first() + 1,changed.size(),changed.size()};
  m_result.append(fmt.format(params));
  m_result.append(CSS_DIFF_CLOSE);
}
 

Example 82

From project LabelUtils, under directory /src/main/java/org/praat/.

Source file: PraatTextFile.java

  15 
vote

public PraatTextFile(File file,Charset charset,EOL eol) throws IOException {
  writer=Files.newWriter(file,charset);
  this.eol=eol.toString();
  number=NumberFormat.getInstance(Locale.US);
  number.setMaximumFractionDigits(32);
  writer.write("File type = \"ooTextFile\"");
  writeLine();
}
 

Example 83

From project Laserschein, under directory /src/laserschein/ui/.

Source file: NumberTweaker.java

  15 
vote

public NumberTweaker(String theTitle,float theDefault,float theMin,float theMax,boolean theIsInt){
  _myMin=theMin;
  _myMax=theMax;
  if (theIsInt) {
    _myFormat=NumberFormat.getIntegerInstance();
  }
 else {
    _myFormat=NumberFormat.getNumberInstance();
  }
  this.setLayout(new GridBagLayout());
  this.setOpaque(false);
  GridBagConstraints myConstraints=new GridBagConstraints();
  _myLabel=new JLabel(theTitle);
  _myLabel.setFocusable(false);
  myConstraints.gridwidth=1;
  myConstraints.fill=GridBagConstraints.HORIZONTAL;
  myConstraints.gridx=0;
  myConstraints.gridy=0;
  this.add(_myLabel,myConstraints);
  _mySlider=new JSlider(0,DIVISIONS);
  _mySlider.setFocusable(true);
  _mySlider.setPreferredSize(new Dimension(200,16));
  myConstraints.gridwidth=3;
  myConstraints.fill=GridBagConstraints.HORIZONTAL;
  myConstraints.gridx=0;
  myConstraints.gridy=1;
  this.add(_mySlider,myConstraints);
  _myTextField=new JTextField();
  _myTextField.setColumns(2);
  _myTextField.setFocusable(true);
  myConstraints.gridwidth=1;
  myConstraints.fill=GridBagConstraints.HORIZONTAL;
  myConstraints.gridx=3;
  myConstraints.gridy=1;
  this.add(_myTextField,myConstraints);
  registerSwingListeners();
  setValue(theDefault,true);
}
 

Example 84

From project liquibase, under directory /liquibase-core/src/main/java/liquibase/change/.

Source file: ColumnConfig.java

  15 
vote

public ColumnConfig setValueNumeric(String valueNumeric){
  if (valueNumeric == null || valueNumeric.equalsIgnoreCase("null")) {
    this.valueNumeric=null;
  }
 else {
    valueNumeric=valueNumeric.replaceFirst("^\\(","");
    valueNumeric=valueNumeric.replaceFirst("\\)$","");
    if (valueNumeric.matches("\\d+\\.?\\d*")) {
      try {
        this.valueNumeric=NumberFormat.getInstance(Locale.US).parse(valueNumeric);
      }
 catch (      ParseException e) {
        throw new RuntimeException(e);
      }
    }
 else {
      this.valueComputed=new DatabaseFunction(valueNumeric);
    }
  }
  return this;
}