Java中的十进制格式

时间:2015-04-24 00:50:31

标签: java decimalformat

我在这里寻找答案,但我无法找到答案,如果有其他帖子谈论它,我很抱歉,但是,我的答案很容易确定但我无法看到它,我怎样才能格式化小数,如:

 7.9820892389040892803E-05

我想格式化这个数字以保持" E"但格式化小数要有:

 7.98203E-05

如果有人能给我看灯,我真的很感激。

3 个答案:

答案 0 :(得分:3)

您可以使用DecimalFormatdocs here):

Symbol  Location    Localized?  Meaning
0       Number      Yes         Digit
#       Number      Yes         Digit, zero shows as absent
.       Number      Yes         Decimal separator or monetary decimal separator 
E       Number      Yes         Separates mantissa and exponent in scientific notation.

例如:

DecimalFormat formatter = new DecimalFormat("#.#####E00");
System.out.println(formatter.format(7.9820892389040892803E-05));
System.out.println(formatter.format(7.98E-05));

输出:

7.98209E-05
7.98E-05

请注意,使用#时,不会打印尾随零。如果您总是想要小数点后五位数,则应使用0

DecimalFormat formatter = new DecimalFormat("0.00000E00");
System.out.println(formatter.format(7.98E-05));

输出:

7.98000E-05

答案 1 :(得分:1)

您可以使用String Formatting

实现此目的

您需要的格式为%.5E(=大写科学记数法中的精度5)

示例:System.out.printf("%.5E", 5/17d);打印2.94118E-01

答案 2 :(得分:0)

使用DeciamlFormat对象...

public static void main(String[] args) {
        double amount = 7.9820892389040892803E-05;
        DecimalFormat df = new DecimalFormat("0.00000E0");
        System.out.println(df.format(amount));
}

结果:

enter image description here