0

我有一个可以包含双精度、整数、ascii 或字节值的字符串值,我将该值放入 JLabel 中。我希望 double 和 long 值采用 .4000000000000而不是 java JLabel 默认打印样式的形式4.0E12。现在我知道字符串中的数据类型是什么,但我不知道如何让 JLabel 只显示双精度和整数值的非科学形式。

这是我到目前为止所尝试的:

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

但这种方法仍然只打印科学形式。

编辑:

我的转换看起来像:

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

也是的,它是一个长值,为了清楚起见,我省略了一些数据类型变量。我不知道这是否适用于所有情况,即使我确实让它工作。我需要它来处理整数、长整数、扩展、双精度和浮点数。

4

1 回答 1

1

您必须使用不同的 JLabel,因为默认情况下它不进行任何转换

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);

显示一个窗口

4000000000000

我只是通过该转换得到以下信息

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));

印刷

400000000
4000000000000
3999999983616   <- due to float rounding error.
4000000000000
于 2011-06-08T15:02:52.840 回答