File tree Expand file tree Collapse file tree
Decimal_To_Fraction/JAVA/todipratik Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ @author Pratik Todi
3+ **/
4+ public class DecimalToFraction {
5+
6+ private long numerator ;
7+ private long denominator ;
8+
9+ public DecimalToFraction (double decimal ) {
10+ String string = Double .toString (decimal );
11+ String [] fraction = string .split ("\\ ." );
12+ numerator = Long .parseLong (fraction [0 ] + "" + fraction [1 ]); // combine the pre-decimal and post-decimal digits to get numerator
13+ denominator = (long ) Math .pow (10 , fraction [1 ].length ()); // ten is raised to power of number of digits after decimal to get
14+ // denominator
15+
16+ // bring the fraction into lowest form
17+ long gcd = greatestCommonDivisor (numerator , denominator );
18+ if (gcd > 0 ) {
19+ numerator /= gcd ;
20+ denominator /= gcd ;
21+ }
22+
23+ }
24+
25+ long greatestCommonDivisor (long num1 , long num2 ) {
26+ // base case
27+ if (num2 == 0 ) {
28+ return num1 ;
29+ }
30+ return greatestCommonDivisor (num2 , num1 % num2 );
31+ }
32+
33+ public String toString () {
34+ return numerator + "/" + denominator ;
35+ }
36+ }
Original file line number Diff line number Diff line change 1+ /**
2+ @author Pratik Todi
3+ **/
4+ class DecimalToFractionDemo {
5+ public static void main (String args []) {
6+ System .out .println (new DecimalToFraction (-1.2345250 )); // fractional equivalent is -49381/40000
7+ System .out .println (new DecimalToFraction (-0 )); // fractional equivalent is 0/1
8+ System .out .println (new DecimalToFraction (1.343 )); // fractional equivalent is 1343/1000
9+ }
10+ }
You can’t perform that action at this time.
0 commit comments