我想在 Java 中打印一个没有指数形式的 double 值。
double dexp = 12345678;
System.out.println("dexp: "+dexp);
它显示了这个 E 符号:1.2345678E7
。
我希望它像这样打印:12345678
防止这种情况的最佳方法是什么?
最佳答案
Java 防止 double 中的 E 表示法:
将 double 转换为普通数的五种不同方法:
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Runner {
public static void main(String[] args) {
double myvalue = 0.00000021d;
//Option 1 Print bare double.
System.out.println(myvalue);
//Option2, use decimalFormat.
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
System.out.println(df.format(myvalue));
//Option 3, use printf.
System.out.printf("%.9f", myvalue);
System.out.println();
//Option 4, convert toBigDecimal and ask for toPlainString().
System.out.print(new BigDecimal(myvalue).toPlainString());
System.out.println();
//Option 5, String.format
System.out.println(String.format("%.12f", myvalue));
}
}
这个程序打印:
2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000
都是相同的值。
Protip:如果你对为什么这些随机数字出现在 double 值中超过某个阈值感到困惑,这个视频解释了:computerphile 为什么 0.1
+0.2
等于0.30000000000001
?
关于java - 如何使用 Java 在没有科学计数法的情况下打印 double 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16098046/