Grammin
Grammin

Reputation: 12205

How do I display non-scientific formatted values on a JLabel and JTextField?

I have a string value that could contain a double, integer, ascii or byte value and I put that value into a JLabel. I would like for the double and long values to be in the form of 4000000000000 instead of the java JLabel default printing style of 4.0E12. Now I know what data type is in the string but I don't know how to make the JLabel display only non-scientific forms for the double and integer values.

Here is what I tried so far:

String str = value; // string that holds the value

switch (var) // var that says which data type my str is
{
  case LONG:
  //convert my string from scientific to non-scientific here
  break;
  case DOUBLE:
  //convert my string from scientific to non-scientific here
  break;
  case ASCII:
  //do nothing
  break;
  ...
}

JLabel label = new JLabel();
label.setText(str); //Want this to be in non-scientific form

but this method still only prints the scientific form.

Edit:

My conversion looks like:

str = new DecimalFormat("#0.###").format(str);

also yes it is a long value, i left out some of the data type variables for clearity. I dont know if this will work for every case though even if i do get it working. I need it to work for integer, long, xtended, double and float.

Upvotes: 0

Views: 2290

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533670

You must be using a different JLabel because it doesn't do any conversion by default

JFrame frame = new JFrame();
JLabel label = new JLabel();
DecimalFormat df = new DecimalFormat("#0.###");
label.setText(df.format(4e12));
frame.add(label);
frame.pack();
frame.setVisible(true);

Displays a window with

4000000000000

I just get the following with that conversion

DecimalFormat df = new DecimalFormat("#0.###");
System.out.println(df.format(400000000));
System.out.println(df.format(4000000000000L));
System.out.println(df.format(4e12f));
System.out.println(df.format(4e12));

prints

400000000
4000000000000
3999999983616   <- due to float rounding error.
4000000000000

Upvotes: 1

Related Questions