pippi longstocking - 1 year ago 97
Java Question

# How to convert decimal to fractions?

What I need to convert decimal to fractions. It is easy to convert to 10's feet.

``````1.5 => 15/10
``````

This can do via this code:

``````public class Rational {

private int num, denom;

public Rational(double d) {
String s = String.valueOf(d);
int digitsDec = s.length() - 1 - s.indexOf('.');
int denom = 1;
for (int i = 0; i < digitsDec; i++) {
d *= 10;
denom *= 10;
}

int num = (int) Math.round(d);
this.num = num;
this.denom = denom;
}

public Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}

public String toString() {
return String.valueOf(num) + "/" + String.valueOf(denom);
}

public static void main(String[] args) {
System.out.println(new Rational(1.5));
}
}
``````

But what I want is

``````1.5 => 3/2
``````

and I don't get how to proceed.
My question is not a duplication. Because other related question is C#. This is java.

You should find the greatest common divisor of the resulted numbers and divide the numerator and denominator by it.

Here is one way to do it:

``````public class Rational {

private int num, denom;

public Rational(double d) {
String s = String.valueOf(d);
int digitsDec = s.length() - 1 - s.indexOf('.');
int denom = 1;
for (int i = 0; i < digitsDec; i++) {
d *= 10;
denom *= 10;
}

int num = (int) Math.round(d);
int g = gcd(num, denom);
this.num = num / g;
this.denom = denom /g;
}

public Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}

public String toString() {
return String.valueOf(num) + "/" + String.valueOf(denom);
}

public static int gcd(int num, int denom) {
....
}

public static void main(String[] args) {
System.out.println(new Rational(1.5));
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download