Skip to content

Commit

Permalink
Merge pull request kennyledet#422 from todipratik/master
Browse files Browse the repository at this point in the history
Added JAVA implementation for decimal to fraction conversion
  • Loading branch information
dalleng committed Oct 26, 2014
2 parents 69c3644 + ef0f324 commit d161826
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Decimal_To_Fraction/JAVA/todipratik/DecimalToFraction.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
@author Pratik Todi
**/
public class DecimalToFraction {

private long numerator;
private long denominator;

public DecimalToFraction(double decimal) {
String string = Double.toString(decimal);
String[] fraction = string.split("\\.");
numerator = Long.parseLong(fraction[0] + "" + fraction[1]); // combine the pre-decimal and post-decimal digits to get numerator
denominator = (long) Math.pow(10, fraction[1].length()); // ten is raised to power of number of digits after decimal to get
// denominator

// bring the fraction into lowest form
long gcd = greatestCommonDivisor(numerator, denominator);
if (gcd > 0) {
numerator /= gcd;
denominator /= gcd;
}

}

long greatestCommonDivisor(long num1, long num2) {
// base case
if (num2 == 0) {
return num1;
}
return greatestCommonDivisor(num2, num1 % num2);
}

public String toString() {
return numerator + "/" + denominator;
}
}
10 changes: 10 additions & 0 deletions Decimal_To_Fraction/JAVA/todipratik/DecimalToFractionDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
@author Pratik Todi
**/
class DecimalToFractionDemo {
public static void main(String args[]) {
System.out.println(new DecimalToFraction(-1.2345250)); // fractional equivalent is -49381/40000
System.out.println(new DecimalToFraction(-0)); // fractional equivalent is 0/1
System.out.println(new DecimalToFraction(1.343)); // fractional equivalent is 1343/1000
}
}

0 comments on commit d161826

Please sign in to comment.