2011-06-08 70 views
0

我有一个字符串值,可以包含一个double,整数,ascii或字节值,我把这个值放入JLabel。我希望将双精度值和长精度值的格式设置为4000000000000而不是java的JLabel默认打印格式4.0E12。现在我知道字符串中的数据类型是什么,但我不知道如何使JLabel只显示双精度和整数值的非科学形式。如何在JLabel和JTextField上显示非科学格式的值?

这里是我试过到目前为止:

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

也肯定这是一个长期的价值,我留下了一些对clearity数据类型的变量。 我不知道这是否会适用于每种情况,即使我确实得到它的工作。我需要它的工作整数,长期,xtended,双和浮动。

+1

听起来像您的转换不正确。你能提供你如何做转换的代码吗? JLabel将仅打印您提供的文本。如果文本错误,则说明文本错误。顺便说一句,你不能有一个'int'值那么大,你的意思是'长'吗? – 2011-06-08 14:54:33

+0

@Peter Lawrey:我已经提供了额外的代码以及int来解释这个问题。 – Grammin 2011-06-08 14:58:42

回答

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 
+0

是的,这是正确的方法,我确实有另外一个,但是这导致它打印错误的值。谢谢! – Grammin 2011-06-08 15:06:19

相关问题