package com.gordonlu.decimal2fraction; import android.app.Activity; import android.content.Context; import com.google.appinventor.components.annotations.*; import com.google.appinventor.components.common.ComponentCategory; import com.google.appinventor.components.runtime.AndroidNonvisibleComponent; import com.google.appinventor.components.runtime.ComponentContainer; import com.google.appinventor.components.runtime.EventDispatcher; import java.util.*; @DesignerComponent( version = 1, description = "Converts a decimal into a fraction.", category = ComponentCategory.EXTENSION, nonVisible = true, iconName = "https://docs.google.com/drawings/d/e/2PACX-1vQCI87PHLBF0jb8QWyYmIRQSjjNW3EFXf-qpsWCvBYkUQ9vEgPAB8SpxcMpblxNpbIYrjCjLrRLIU2c/pub?w=16&h=16") @SimpleObject(external = true) //Libraries @UsesLibraries(libraries = "") //Permissions @UsesPermissions(permissionNames = "") public class Decimal2Fraction extends AndroidNonvisibleComponent { //Activity and Context private Context context; private Activity activity; public Decimal2Fraction(ComponentContainer container){ super(container.$form()); this.activity = container.$context(); this.context = container.$context(); } @SimpleFunction(description = "Turns a decimal into a fraction.") public static String DecimalToFraction(double number, String separator) { double intVal = Math.floor(number); double fVal = number - intVal; final long pVal = 1000000000; long gcdVal = gcd(Math.round(fVal * pVal), pVal); long num = Math.round(fVal * pVal) / gcdVal; long deno = pVal / gcdVal; return ((long)(intVal * deno) + num + separator + deno); } @SimpleFunction(description = "Gets the numerator from the decimal.") public static long GetNumerator(double number) { double intVal = Math.floor(number); double fVal = number - intVal; final long pVal = 1000000000; long gcdVal = gcd(Math.round(fVal * pVal), pVal); long num = Math.round(fVal * pVal) / gcdVal; long deno = pVal / gcdVal; return ((long)(intVal * deno) + num); } @SimpleFunction(description = "Gets the denominator from the decimal.") public static long GetDenominator(double number) { double intVal = Math.floor(number); double fVal = number - intVal; final long pVal = 1000000000; long gcdVal = gcd(Math.round(fVal * pVal), pVal); long num = Math.round(fVal * pVal) / gcdVal; long deno = pVal / gcdVal; return ((long)deno); } private static long gcd(long a, long b) { if (a == 0) return b; else if (b == 0) return a; if (a < b) return gcd(a, b % a); else return gcd(b, a % b); } }