我想在Java中打印一个没有指数形式的双值。

double dexp = 12345678;
System.out.println("dexp: "+dexp);

它显示了这个E符号:1.2345678E7。

我希望它像这样打印:12345678

预防这种情况的最好方法是什么?


当前回答

我需要将一些double转换为货币值,发现大多数解决方案都是可以的,但不适合我。

十进制格式最终是我的方式,所以这是我所做的:

   public String foo(double value) //Got here 6.743240136E7 or something..
    {
        DecimalFormat formatter;

        if(value - (int)value > 0.0)
            formatter = new DecimalFormat("0.00"); // Here you can also deal with rounding if you wish..
        else
            formatter = new DecimalFormat("0");

        return formatter.format(value);
    }

正如你所看到的,如果数字是自然的,我得到-比如说- 20000000而不是2E7(等等)-没有任何小数点。

如果是小数,就只能得到两个小数。

其他回答

这不仅适用于整数:

double dexp = 12345678.12345678;
BigDecimal bigDecimal = new BigDecimal(Double.toString(dexp));
System.out.println("dexp: "+ bigDecimal.toPlainString());

Java/Kotlin编译器将任何大于9999999(大于或等于1000万)的值转换为科学计数法。Epsilion符号。

示例:12345678被转换为1.2345678E7

使用此代码避免自动转换为科学计数法:

fun setTotalSalesValue(String total) {
        var valueWithoutEpsilon = total.toBigDecimal()
        /* Set the converted value to your android text view using setText() function */
        salesTextView.setText( valueWithoutEpsilon.toPlainString() )
    }

我认为每个人的想法都是正确的,但并非所有的答案都是直截了当的。 我认为这是一段非常有用的代码。下面是一些可行的方法:

System.out.println(String.format("%.8f", EnterYourDoubleVariableHere));

”。“8”是您设置要显示的小数点后数位的位置。

我正在使用Eclipse,它工作没有问题。

希望这对你有帮助。我将感激任何反馈!

下面的代码检测所提供的数字是否以科学计数法表示。如果是这样,则在正常表示中使用最多“25”位数表示。

 static String convertFromScientificNotation(double number) {
    // Check if in scientific notation
    if (String.valueOf(number).toLowerCase().contains("e")) {
        System.out.println("The scientific notation number'"
                + number
                + "' detected, it will be converted to normal representation with 25 maximum fraction digits.");
        NumberFormat formatter = new DecimalFormat();
        formatter.setMaximumFractionDigits(25);
        return formatter.format(number);
    } else
        return String.valueOf(number);
}

你可以使用printf()与%f:

double dexp = 12345678;
System.out.printf("dexp: %f\n", dexp);

这将打印出dexp: 12345678.000000。如果你不想要小数部分,就用

System.out.printf("dexp: %.0f\n", dexp);

0在%。0f表示小数部分有0个位置,即没有小数部分。如果你想打印所需小数位数的小数部分,那么只需提供像%.8f这样的数字,而不是0。默认情况下,小数部分打印到小数点后6位。

这使用文档中解释的格式说明符语言。

在原始代码中使用的默认toString()格式在这里详细说明。