In Java, I am trying to find a way to convert a float number into a fraction string. For example:
float num = 1.33333;
String numStr = Convert(num); // Shoul
Extract the fractional part of the number (for example, ((int) 0.5 + 1) - 0.5
, then divide one by the result (1 / 0.5
). You'll get the denominator of the fraction. Then cast the float to an int, and you'll get the integer part. Then concatenate both.
It's just a simple solution, and will work only if the numerator of the fraction is 1.
double n = 1.2f;
int denominator = 1 / (Math.abs(n - (int) n - 0.0001)); //- 0.0001 so the division doesn't get affected by the float point aproximated representation
int units = (int) n;
int numerator = units * denominator + 1;
System.out.println("" + numerator + "/" + denominator); //6/5
System.out.println("" + units + " 1/" + denominator); //1 1/5