forked from kennyledet/Algorithm-Implementations
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request kennyledet#422 from todipratik/master
Added JAVA implementation for decimal to fraction conversion
- Loading branch information
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
36 changes: 36 additions & 0 deletions
36
Decimal_To_Fraction/JAVA/todipratik/DecimalToFraction.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
10
Decimal_To_Fraction/JAVA/todipratik/DecimalToFractionDemo.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |