-
-
Save chayanforyou/63c4ef3905c2afb78603e753de94784d to your computer and use it in GitHub Desktop.
Decimal to Fraction Converter
This file contains hidden or 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
/* | |
* Converts Decimals to Fractions | |
* | |
*/ | |
package simpleai; | |
/** | |
* | |
* @author sarabeth | |
*/ | |
import java.util.*; | |
public class ForBrett { | |
public static void main(String[] args) { | |
double d = 3.65; | |
String text = Double.toString(Math.abs(d)); | |
int integerPlaces = text.indexOf('.'); | |
int decimalPlaces = text.length() - integerPlaces - 1; | |
System.out.println(text); | |
//whole number | |
if (text.length() == 3 && text.charAt(text.length() - 1) == '0') { | |
decimalPlaces = 0; | |
} else { | |
double converted_d = d*Math.pow(10, decimalPlaces); | |
int divisor = GCD((int)converted_d, (int)Math.pow(10, decimalPlaces)); | |
System.out.println( (converted_d/divisor) + "/" + ((Math.pow(10, decimalPlaces))/divisor)); | |
} | |
} | |
public static int GCD(int num, int denom) { | |
if (denom == 0) { | |
return num; | |
} | |
return GCD(denom, num % denom); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment