Is there a proper way for converting a double value to a BigInteger value and later back? In the best case without loosing data. The problem is, that I don't know how many decimal places the double values have. But I need this conversion for an Algorithm which only works with non decimal values. After the Algorithm finishes I have to convert it back.
An easy example what I need: for example the sum of 2 double values but the "sum" function works only with BigInteger.
You can do it in 5 steps:
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
sum
methodOutput:
0.1 + 0.1 = 0.2
0.1 + 10.1 = 10.2
0.1245 + 17.0 = 17.1245
Code:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With