Java Fraction Base Conversion

by androboy   Last Updated August 14, 2019 18:26 PM

I want to convert a source base number to a destination base number, but I have a problem with fractions. When I trying to convert 10.234 (base10) to base 7 = 13.14315 it works perfectly, or aaaaa.0 (base16) to base 24 = 22df2 it also works.

But when I try to convert aaaaa.cdefb0 (base16) to base 24 = 22df2.j78da it doesn't work. I can't calculate fraction part and I get 22df2 as the answer

my code for base conversion :

private static String baseConversion(String number,
                                         int sBase, int dBase) {
        return Long.toString(
                Long.parseLong(number, sBase),
                dBase);
    }

my code for fraction conversion :

private static String fractionConversion(double fraction, int dBase) {
        StringBuilder output = new StringBuilder(".");

        for (int i = 0; i < PRECISION; i++) {
            fraction *= dBase;
            output.append(Long.parseLong(Integer.toString((int) fraction)));
            fraction -= Long.parseLong(Integer.toString((int) fraction));
        }

        return output.toString();
    }


Answers 1


In your code below you should be appending a symbol for the base, not a number. Use the number to index into an array of symbols for the base.

And I recommend using integers for your remainder and product computations as you will eventually lose precision using floating point values.

        for (int i = 0; i < PRECISION; i++) {
            fraction *= dBase;

            // what are you appending here?  It should be a symbol
            output.append(Long.parseLong(Integer.toString((int) fraction)));

            fraction -= Long.parseLong(Integer.toString((int) fraction));
        }
WJS
WJS
August 14, 2019 18:18 PM

Related Questions



Converting Decimal to Octal Using Bitwise Operators

Updated September 01, 2017 20:26 PM


Counting with signed powers of 3

Updated January 22, 2018 09:26 AM