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:
Given double x >= 0, int p, int q, find p/q as closest approximation:
So (not tested):
public static Rational toFraction(double x) {
// Approximate x with p/q.
final double eps = 0.000_001;
int pfound = (int) Math.round(x);
int qfound = 1;
double errorfound = Math.abs(x - pfound);
for (int q = 2; q < 100 && error > eps; ++q) {
int p = (int) (x * q);
for (int i = 0; i < 2; ++i) { // below and above x
double error = Math.abs(x - ((double) p / q));
if (error < errorfound) {
pfound = p;
qfound = q;
errorfound = error;
}
++p;
}
}
return new Rational(pfound, qfound);
}
You could try it for Math.PI and E.