gpt4 book ai didi

java - 如何在 JLabel 和 JTextField 上显示非科学格式的值?

转载 作者:行者123 更新时间:2023-12-01 15:50:02 24 4
gpt4 key购买 nike

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

这是我迄今为止尝试过的:

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

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

最佳答案

您必须使用不同的 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

关于java - 如何在 JLabel 和 JTextField 上显示非科学格式的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6280755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com