Converting a float into a string fraction representation

后端 未结 6 875
一整个雨季
一整个雨季 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条回答
  •  萌比男神i
    2021-01-17 20:32

    Assume you have "0.1234567", then count how many numbers after the decimal point (which is 7). then multiply the number with 10 ^ 7, now you have "1234567".

    divide 1234567 over 10 ^ 7. Then, simplify the fraction using the GCD of the two numbers.

    0.1234567 * 10000000 = 1234567
    => 1234567 / 10000000
    => System.out.println(1234567 / gcd(1234567,10000000) + "/" + 10000000/gcd(1234567,10000000));
    

提交回复
热议问题