将大科学数字转换为长

Converting large scientific number to long

我已经花了很长时间尝试转换 java 中的数字 1.2846202978398e+19,但没有成功。目前我正在尝试做的事情 (long)Double.parseDouble(hashes),但这给出了 9223372036854775807,这显然是不正确的。实际数字应该类似于 12855103593745000000。

使用 int val = new BigDecimal(stringValue).intValue(); returns -134589568 因为它无法保留结果。将代码切换为 long val = new BigDecimal(hashes).longValue(); 会得到 -5600541095311551616,这也是不正确的。

我假设这是由于 double 与 long 相比的大小。

有什么想法吗?

您是否尝试使用 String.format :

String result = String.format("%.0f", Double.parseDouble("1.2846202978398e+19"));
System.out.println(result);

输出

12846202978398000000

编辑

为什么你不用BigDecimal做算术运算,例如:

String str = "1.2846202978398e+19";
BigDecimal d = new BigDecimal(str).multiply(BigDecimal.TEN);
//                                 ^^^^^^^^------example of arithmetic operations


System.out.println(String.format("%.0f", d));
System.out.println(String.format("%.0f", Double.parseDouble(str)));

输出

128462029783980000000
12846202978398000000

您的值超过 long 的最大大小。在这种情况下你不能使用 long。 尝试

BigDecimal value = new BigDecimal("1.2846202978398e+19");

之后,您可以调用

value.toBigInteger()

 value.toBigIntegerExact()

如果需要。

怎么样:

System.out.println(new BigDecimal("1.2846202978398e+19").toBigInteger());