I'm trying to create a number class which can hold values from 4.9E-324e-1.7976931348623157E308
to 1.7976931348623157E308e1.7976931348623157E308
in both signs. (yes, the exponent is also a double)
My number class is in base 2.
I have all the arithmetic working, but I'm having trouble trying to display it as a string in the format ...#####.#####...
.
This is what I've come up with.
@Nonnull
public String toReadableString(@Nonnull MathContext context) {
try {
final BigDecimal mantissa = BigDecimal.valueOf(y);
final BigDecimal exponentiation = BigDecimal.valueOf(2).pow((int) x, context);
// The above line throws an ArithmeticException if magnitude(x) > 999999999
// This is defined in BigDecimal, and I can't change the limit
final BigDecimal result = mantissa.multiply(exponentiation);
return result.toPlainString();
} catch (final ArithmeticException e) {
return "OUT_OF_DISPLAYABLE_RANGE";
}
}
I've tried searching for other methods of converting base 2 to base 10, but every method I could find involves actually calculating the value as a double
, which would obviously not work for most values of this number class.
Summary
I need a function toReadableString() : String
which can reliably convert base 2 scientific notation in the form of 2^double * double
for an arbitrary n
number of decimal points.
Any help would be great, even if it's not a complete solution.
For reference, here's the structure of my number class.
// This extends Vector2 to use all the features provided by the vector class
public class RealNumber extends Vector2 implements Comparable<RealNumber> {
public RealNumber(double val);
public RealNumber(double exponent, double mantissa);
public final double exponent();
public final double mantissa();
// Code ommitted
public String toReadableString(MathContext context); // Body defined above
}
I know this is very impractical and abstract. I personally like that kind of stuff, and this is a purely personal project which I'm doing for fun.
I've tried:
- Converting
exponent
andmantissa
toBigDecimal
to calculate the value (BigDecimal.pow(int) causes a problem) - The current approach
- Just using
double
(of course it doesn't work) - Iterating through each digit and adding the value to a
BigDecimal
(maybe there was an error in my code, but didn't work)