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:
I tried adding this as an edit, but it was denied. This answer builds off of @Hristo93's answer but finishes the gcd method:
public class DecimalToFraction {
private int numerator, denominator;
public Rational(double decimal) {
String string = String.valueOf(decimal);
int digitsDec = string.length() - 1 - s.indexOf('.');
int denominator = 1;
for (int i = 0; i < digitsDec; i++) {
decimal *= 10;
denominator *= 10;
}
int numerator = (int) Math.round(decimal);
int gcd = gcd(numerator, denominator);
this.numerator = numerator / gcd;
this.denominator = denominator /gcd;
}
public static int gcd(int numerator, int denom) {
return denominator == 0 ? numerator : gcm(denominator, numerator % denominator);
}
public String toString() {
return String.valueOf(numerator) + "/" + String.valueOf(denominator);
}
public static void main(String[] args) {
System.out.println(new Rational(1.5));
}
}