2016-11-14 42 views
-4

我似乎無法找到將小數值轉換爲分數形式的簡單方法。我需要在較大程序中使用此方法,因此該方法應傳遞一個double值並返回一個字符串。將小數轉換爲分數形式方法(Java)

編輯:對不起,新的在這裏。我只想要一個關於如何製作一個的想法。我見過的例子分配了自己的值來使用。該方法看起來像

public string convertype(double decimal){ 
     (Statements) 
     return fraction; 
} 
+1

據我所知,有這樣的號已經取得功能。你必須自己創建它。 此外,你的問題是不夠具體的SO標準。 – Mornor

回答

0
public class Fraction { 

    private int numerator, denominator; 

    public Fraction(double decimal) { 
     String stringNumber = String.valueOf(decimal); 
     int numberDigitsDecimals = stringNumber.length() - 1 - stringNumber.indexOf('.'); 
     int denominator = 1; 
     for (int i = 0; i < numberDigitsDecimals; i++) { 
      decimal *= 10; 
      denominator *= 10; 
     } 

     int numerator = (int) Math.round(decimal); 
     int greatestCommonFactor = greatestCommonFactor(numerator, denominator); 
     this.numerator = numerator/greatestCommonFactor; 
     this.denominator = denominator/greatestCommonFactor; 
    } 

    public String toString() { 
     return String.valueOf(numerator) + "/" + String.valueOf(denominator); 
    } 

    public static int greatestCommonFactor(int num, int denom) { 
     if (denom == 0) { 
      return num; 
     } 
     return greatestCommonFactor(denom, num % denom); 
    } 

    public static void main(String[] args) { 
     System.out.println(new Fraction(0.75)); 
    } 
} 
+0

試圖將此作爲我的方法類中的對象使用,對此有何看法? – akhg2235

+0

@ akhg2235只能像這樣在你的方法中調用一個Fraction類實例。 '公共字符串轉換類型(雙十進制){ return(new Fraction(decimal))。toString(); }' – johnnynemonic

0
public class NewClass { 

    public static void main(String[] args) { 
     System.out.println(convertype(0.75)); 
    } 
    public static String convertype(double decimal){ 
     int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits 
     BigInteger numerator = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75 
     BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint)));  // 10^2 is your denominator 
     int gcd = numerator.gcd(denominator).intValue();           // calculate the greatest common divisor of numerator and denominator 
     if (gcd > 1){                    // gcd(75,100) = 25 
     return String.valueOf(numerator.intValue()/gcd) +"/" + String.valueOf(denominator.intValue()/gcd); // return 75/25/100/25 = 3/4 
     } 
     else{ 
     return String.valueOf(numerator) +"/" + String.valueOf(denominator);    // if gcd = 1 which means nothing to simplify just return numerator/denominator 
     }  
    } 
}