Java(初学者)将科学计数法转换为十进制

12

如果

double d =  1.999e-4

我希望输出结果为0.0001999。

我该如何做?


您应该选择一个有帮助的答案并点赞。 - jahroy
5个回答

9
NumberFormat formatter = new DecimalFormat("###.#####");  

String f = formatter.format(d);  

您可以探索NumberFormat类的子类,以了解更多细节。

7

我猜BigDecimal类中有一个叫做toPlainString()的方法。

举一个例子,如果BigDecimal是1.23e-8,则该方法返回0.0000000124。

BigDecimal d = new BigDecimal("1.23E-8");

System.out.println(d.toPlainString());

上面的代码打印出0.0000000123,然后您可以根据您的要求处理该字符串。

我的Excel表格编号是42.063706,但返回的是42.06370600000000337104211212135851383209228515625。 - Abdullah Nurum
@AbdullahNurum 你使用什么方法读取Excel表格并构建BigDecimal对象?当我使用字符串字面量“42.063706”构建它时,它输出了正确的结果(与输入相同)。确保在读取和创建BigDecimal对象之间不将其存储为浮点值。在此期间应将其保留为字符串,以避免失去精度。 - theferrit32

5
你可以像这样做:
    double d = 1.999e-4;
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(7);
    System.out.println(nf.format(d));

请查看NumberFormat的方法文档,以您希望的方式格式化您的double

DecimalFormatNumberFormat的特例,因为它的构造函数说明,我认为您在此情况下不需要其功能。如果您感到困惑,请查看它们的文档。使用NumberFormat的工厂方法getInstance()方便您操作。


非常感谢!(顺便问一下,我应该使用NumberFormat还是DecimalFormat?) - hibc

3
如果你只想像那样打印,请按如下方式操作。
System.out.printf("%1$.10f", d);

您可以更改10f,其中10表示您想要的小数位数。

非常感谢!1$ = ?? 是什么意思? - hibc
1$表示参数索引,如果你使用System.out.printf("%3$.10f", e,f,d);,你需要使用3$作为目标参数索引,因为它对应的是d。详见此处:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html。 - specialscope

0

请看一下

java.text.DecimalFormat

并且

java.text.DecimalFormatSymbols

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接