How to convert decimal to fractions?

前端 未结 10 2189
心在旅途
心在旅途 2020-12-06 06:26

What I need to convert decimal to fractions. It is easy to convert to 10\'s feet.

1.5 => 15/10

This can do via this code:



        
10条回答
  •  遥遥无期
    2020-12-06 07:05

    Not only for the decimal number 1.5, for all you can use the following steps:

    1. Find Number of decimal digits:

      double d = 1.5050;//Example I used

      double d1 = 1;

      String text = Double.toString(Math.abs(d));

      int integerPlaces = text.indexOf('.');

      int decimalPlaces = text.length() - integerPlaces - 1;

      System.out.println(decimalPlaces);//4

    2. Then convert to integer:

      static int ipower(int base, int exp) {

          int result = 1;
          for (int i = 1; i <= exp; i++) {
              result *= base;           
          }            
          return result;
      }
      

      //using the method

      int i = (int) (d*ipower(10, decimalPlaces));

      int i1 = (int) (d1*ipower(10, decimalPlaces));

      System.out.println("i=" + i + " i1 =" +i1);//i=1505 i1 =1000

    3. Then find highest common factor

      private static int commonFactor(int num, int divisor) {

          if (divisor == 0) {
              return num;
          }
      
          return commonFactor(divisor, num % divisor);
      }
      

    //using common factor

    int commonfactor = commonFactor(i, i1);

    System.out.println(commonfactor);//5

    1. Finally print results:

      System.out.println(i/commonfactor + "/" + i1/commonfactor);//301/200

    Here you can find:

      public static void main(String[] args) {
    
            double d = 1.5050;
            double d1 = 1;
    
            String text = Double.toString(Math.abs(d));
            int integerPlaces = text.indexOf('.');
            int decimalPlaces = text.length() - integerPlaces - 1;
    
            System.out.println(decimalPlaces);
            System.out.println(ipower(10, decimalPlaces));
    
            int i = (int) (d*ipower(10, decimalPlaces));
            int i1 = (int) (d1*ipower(10, decimalPlaces));      
    
            System.out.println("i=" + i + " i1 =" +i1);
    
            int commonfactor = commonFactor(i, i1);
            System.out.println(commonfactor);
    
            System.out.println(i/commonfactor + "/" + i1/commonfactor);
    
    
        }
    
        static int ipower(int base, int exp) {
            int result = 1;
            for (int i = 1; i <= exp; i++) {
                result *= base;           
            }
    
            return result;
        }
    
        private static int commonFactor(int num, int divisor) {
            if (divisor == 0) {
                return num;
            }
            return commonFactor(divisor, num % divisor);
        }
    

提交回复
热议问题