Converting a float into a string fraction representation

后端 未结 6 769
一整个雨季
一整个雨季 2021-01-17 20:23

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         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-17 20:50

    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
    

提交回复
热议问题