If I have a structure like this:
public class DoubleData {
public long integer;
public int floatingPartOffset; // >=0
public long floatingPart; // >= 0
public int exponent;
public DoubleData(long integer, long floatingPart, int floatingPartOffset, int exponent)
{
this.integer = integer;
this.floatingPart = floatingPart;
this.exponent = exponent;
this.floatingPartOffset = floatingPartOffset
}
public double toDouble()
}
And I want to implement a behavior like this:
DoubleData(123,567,1,0).toDouble() -> 123.0567
DoubleData(-123,567,0,0).toDouble() -> -123.567
DoubleData(-123,567,2,-8).toDouble() -> -123.00567e-8
How to achieve this? Are there any libraries for that? If it's easier I can replace long and int with byte[] And how to make it as efficient as possible?
CodePudding user response:
You can concatenate the parts together as a String
and convert it to a double
with Double.parseDouble
.
public double toDouble(){
return Double.parseDouble(integer "." floatingPart "e" exponent);
}
CodePudding user response:
That is just math operation using the 3 values
public double toDouble() {
double floatingPartExponent = Math.pow(10, Math.ceil(Math.log10(floatingPart)));
double floatSign = Math.signum(integer);
return (integer floatSign * floatingPart / floatingPartExponent) * Math.pow(10, exponent);
}
CodePudding user response:
They are many ways to do that here is one of them.
import java.math.BigDecimal;
import java.math.MathContext;
public class DoubleData {
public long integer;
public long floatingPart; // >= 0
public int exponent;
public DoubleData(long integer, long floatingPart, int exponent) {
this.integer = integer;
this.floatingPart = floatingPart;
this.exponent = exponent;
}
public double toDouble() {
String stringRepresentation = integer "." floatingPart;
BigDecimal bigDecimal = new BigDecimal(stringRepresentation, new MathContext(exponent));
return bigDecimal.doubleValue();
}
}