Skip to content

Instantly share code, notes, and snippets.

@chayanforyou
Forked from jaffes2/DecimalToFraction
Created September 28, 2022 04:00
Show Gist options
  • Save chayanforyou/63c4ef3905c2afb78603e753de94784d to your computer and use it in GitHub Desktop.
Save chayanforyou/63c4ef3905c2afb78603e753de94784d to your computer and use it in GitHub Desktop.
Decimal to Fraction Converter
/*
* 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