使用Java将double值转换为BigInteger值的最佳方法

Dan*_*sig 4 java double biginteger

有没有一种方法可以将double值转换为BigInteger值,然后再返回?在最好的情况下,不会丢失数据.问题是,我不知道double值有多少小数位.但我需要这种转换为一种只适用于非十进制值的算法.算法完成后,我必须将其转换回来.

我需要的一个简单示例:例如,2个double值的总和,但"sum"函数仅适用于BigInteger.

ass*_*ias 5

您可以通过5个步骤完成:

double d1 = 0.1; //your original double
BigDecimal bd1 = new BigDecimal(d1); //convert to BigDecimal
BigInteger bi = bd1.unscaledValue(); //convert to BigInteger
//here do your stuff with the BigInteger
BigDecimal bd2 = new BigDecimal(bi, bd1.scale()); //back to BigDecimal, applying scale
double d2 = bd2.doubleValue(); //convert to double
Run Code Online (Sandbox Code Playgroud)

应用于sum方法的完整示例

输出:

0.1 + 0.1 = 0.2
0.1 + 10.1 = 10.2
0.1245 + 17.0 = 17.1245

码:

public static void main(String[] args) {
  test(0.1, 0.1);
  test(0.1, 10.1);
  test(0.1245, 17);
}

private static void test(double d1, double d2) {
  System.out.println(d1 + " + " + d2 + " = " + sum(d1, d2));
}

private static double sum(double d1, double d2) {
  BigDecimal bd1 = new BigDecimal(d1);
  BigDecimal bd2 = new BigDecimal(d2);

  int shift = Integer.max(bd1.scale(), bd2.scale());

  BigInteger bi1 = bd1.scaleByPowerOfTen(shift).toBigInteger();
  BigInteger bi2 = bd2.scaleByPowerOfTen(shift).toBigInteger();

  BigInteger sum = sum(bi1, bi2);

  return new BigDecimal(sum, shift).doubleValue();
}

private static BigInteger sum(BigInteger i1, BigInteger i2) {
  return i1.add(i2);
}
Run Code Online (Sandbox Code Playgroud)

  • @assylias我已经根据这个添加了一个答案,但使用了最大规模的想法.它包括对1074来自何处的解释. (2认同)