Introduction
A simple extension that converts a decimal number to a fraction.
Version: 2
Package name: com.gordonlu.decimal2fraction
Release date: 2022-01-20T10:00:00Z
Documentation
DecimalToFraction
Converts a decimal to a fraction.
Returns: text
Parameters: number = number (double), separator = text
GetDenominator
Returns the denominator of the fraction from the decimal.
Parameters: number = double
GetNumerator
Returns the numerator of the fraction from the decimal.
Parameters: number = double
Can this be done with built-in blocks?
Yes and no. It really depends on what decimals you are using. This is the best built-in blocks method for converting a decimal to a fraction (proposed by this AI2 post).
If you put this procedure with the extension, you see no difference.
However, as the decimal becomes more accurate, the use of the procedure is questionable. This is because App Inventor (and its distributions) floats decimals with decimal digits > 5.
Downloads
com.gordonlu.decimal2fracion.aix (6.4 KB)
Open Source
Apart from importing java.util *
, you only need these.
@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);
}
}
Made with Niotron IDE.
Kindly PM me if you have any questions! Also, if you like my extension, please like it! It takes some effort for me to make itโฆ
Votes and likes tell me the general user feedback of my extension. If you read this extension, please take 20 seconds to drop by and give a like!
If you have any features that you want to add and you know the code, PM me.
Gordon Lu