我想在Java中打印一个没有指数形式的双值。
double dexp = 12345678;
System.out.println("dexp: "+dexp);
它显示了这个E符号:1.2345678E7。
我希望它像这样打印:12345678
预防这种情况的最好方法是什么?
我想在Java中打印一个没有指数形式的双值。
double dexp = 12345678;
System.out.println("dexp: "+dexp);
它显示了这个E符号:1.2345678E7。
我希望它像这样打印:12345678
预防这种情况的最好方法是什么?
当前回答
我得到了另一个涉及BigDecimal的toPlainString()的解决方案,但这次使用了string构造函数,这在javadoc中是推荐的:
此构造函数与Float返回的值兼容。toString和Double.toString。这通常是将浮点数或双精度浮点数转换为BigDecimal的首选方法,因为它不会受到BigDecimal(double)构造函数的不可预测性的影响。
它的最短形式是这样的:
return new BigDecimal(myDouble.toString()).stripTrailingZeros().toPlainString();
NaN和无限值必须额外检查,所以它的完整形式如下:
public static String doubleToString(Double d) {
if (d == null)
return null;
if (d.isNaN() || d.isInfinite())
return d.toString();
return new BigDecimal(d.toString()).stripTrailingZeros().toPlainString();
}
这也可以复制/粘贴,以很好地与Float一起工作。
对于Java 7及以下版本,对于任何零值double,这将导致“0.0”,因此您需要添加:
if (d.doubleValue() == 0)
return "0";
其他回答
对于用double表示的整数值,可以使用这段代码,它比其他解决方案快得多。
public static String doubleToString(final double d) {
// check for integer, also see https://stackoverflow.com/a/9898613/868941 and
// https://github.com/google/guava/blob/master/guava/src/com/google/common/math/DoubleMath.java
if (isMathematicalInteger(d)) {
return Long.toString((long)d);
} else {
// or use any of the solutions provided by others, this is the best
DecimalFormat df =
new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
return df.format(d);
}
}
// Java 8+
public static boolean isMathematicalInteger(final double d) {
return StrictMath.rint(d) == d && Double.isFinite(d);
}
下面的代码检测所提供的数字是否以科学计数法表示。如果是这样,则在正常表示中使用最多“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);
}
这不仅适用于整数:
double dexp = 12345678.12345678;
BigDecimal bigDecimal = new BigDecimal(Double.toString(dexp));
System.out.println("dexp: "+ bigDecimal.toPlainString());
在我的生产代码中,当我使用它作为math.Eval()函数的字符串输入时,我遇到了同样的问题,该函数接受“x + 20 / 50”这样的字符串
我看了几百篇文章……最后我选择了这个,因为它的速度。因为Eval函数最终会将其转换回自己的数字格式,而math.Eval()不支持其他方法返回的尾随E-07,而且任何超过5 dp的内容对我的应用程序来说都太详细了。
这现在被用于有1000多个用户的应用程序的生产代码中……
double value = 0.0002111d;
String s = Double.toString(((int)(value * 100000.0d))/100000.0d); // Round to 5 dp
s display as: 0.00021
使用字符串。格式(“%。0 f”,数量)
%。0f表示0小数
String numSring = String.format ("%.0f", firstNumber);
System.out.println(numString);