espirio
espirio

Reputation: 189

Double convert to Fraction

I want a double convert value into a fraction (in Java).

Example: 0.33333 -> 1/3

I have many examples to Fraction found, but this does not help me. The numbers are always between 0 to 1.

Has perhaps anyone have an idea?

Tahnks,

Upvotes: 1

Views: 1136

Answers (1)

cshu
cshu

Reputation: 5944

I guess you want the approximate fraction representation of a double value (like your example)

A simple way is to try denominators one by one:

double doubleVal = 0.33333;
double negligibleRatio = 0.01;

for(int i=1;;i++){
    double tem = doubleVal/(1D/i);
    if(Math.abs(tem-Math.round(tem))<negligibleRatio){
        System.out.println(Math.round(tem)+"/"+i);
        break;
    }
}

This prints 1/3. If you set double doubleVal = 0.6363636;, it prints 7/11.

You can change negligibleRatio to a bigger value if you want more succinct fraction result.

Upvotes: 3

Related Questions