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.
In this case, 0.75 has two numbers after the decimal, so, we place 100 in the denominator and remove the decimal point. It should be noted that 3/4 and 75/100 are equivalent fractions. The value of 0.75 as a fraction is 3/4.
Answer: 0.33333 as a fraction is 1/3.
3.5 in fraction form is 7/2 or 35/10. The number of digits after the decimal point is equal to the number of zeros following the digit 1 in the denominator of the fractional form.
static private String convertDecimalToFraction(double x){
if (x < 0){
return "-" + convertDecimalToFraction(-x);
}
double tolerance = 1.0E-6;
double h1=1; double h2=0;
double k1=0; double k2=1;
double b = x;
do {
double a = Math.floor(b);
double aux = h1; h1 = a*h1+h2; h2 = aux;
aux = k1; k1 = a*k1+k2; k2 = aux;
b = 1/(b-a);
} while (Math.abs(x-h1/k1) > x*tolerance);
return h1+"/"+k1;
}
I got this answer from here. All I had to do is convert his answer to 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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With