Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a float into a string fraction representation

In Java, I am trying to find a way to convert a float number into a fraction string. For example:

float num = 1.33333;
String numStr = Convert(num); // Should return "1 1/3"

float num2 = 1.333;
String numStr2 = Convert(num2); // Should also return "1 1/3"

float num3 = 0.5;
String numStr3 = Convert(num3); // Should return "1/2"

float num4 = 2.25;
String numStr4 = Convert(num4); // Should return "2 1/4"

Any ideas how to do this in Java?

like image 847
Icemanind Avatar asked May 11 '11 18:05

Icemanind


People also ask

How do you turn a float into a fraction?

To do so, we first let the algorithms above give us a fraction (exact or approximate). Then, we post-process it by changing the denominator into the desired number. Then, we round the numerator to the nearest integer and get a fraction with the denominator we wanted.

Is float a fractional number?

A float is a rational number expressed in floating-point format, usually to base 10 or decimal. What does that mean? Consider the number 110. We can write it as 1.1 x 102, where the decimal point one digit before the end indicates that that first number is really the fraction 11 / 10.


1 Answers

The simplest approach might be to use trial and error.

public static String toFraction(double d, int factor) {
    StringBuilder sb = new StringBuilder();
    if (d < 0) {
        sb.append('-');
        d = -d;
    }
    long l = (long) d;
    if (l != 0) sb.append(l);
    d -= l;
    double error = Math.abs(d);
    int bestDenominator = 1;
    for(int i=2;i<=factor;i++) {
        double error2 = Math.abs(d - (double) Math.round(d * i) / i);
        if (error2 < error) {
            error = error2;
            bestDenominator = i;
        }
    }
    if (bestDenominator > 1)
        sb.append(' ').append(Math.round(d * bestDenominator)).append('/') .append(bestDenominator);
    return sb.toString();
}

public static void main(String... args)  {
    System.out.println(toFraction(1.3333, 1000));
    System.out.println(toFraction(1.1428, 1000));
    for(int i=1;i<100000000;i*=10) {
        System.out.println("PI "+i+": "+toFraction(3.1415926535897932385, i));
    }
}

prints

1 1/3
1 1/7
PI 1: 3
PI 10: 3 1/7
PI 100: 3 14/99
PI 1000: 3 16/113
PI 10000: 3 16/113
PI 100000: 3 14093/99532
PI 1000000: 3 140914/995207
PI 10000000: 3 244252/1725033
like image 165
Peter Lawrey Avatar answered Oct 06 '22 16:10

Peter Lawrey