Game Maker Games, Articles, Tutorials & More

Game Maker Network


Howdy, Guest! Please sign in or register an account.

Print

decimal2fraction

By Daniel · December 24, 2008

Converts a decimal number into a fraction (represented as a string)

/*
 * decimal2fraction(n, precision)
 * Returns a string of the form numerator/denominator.
 *
 * The precision is adjustable, but it probably shouldn't exceed ~9. GM can
 * accurately represent fairly large numbers, but many of its numeric
 * functions epic fail on rather small inputs. For example, floor(10000000000)
 * evaluates to 1410065408 (on a 32-bit system, at least).
 */

var n, num, den, a, b, tmp, precision, limit;

n = argument0;
precision = argument1;

// Begin with the original number divided by 1
num = n;
den = 1;

// Get rid of the decimal in the numerator by expanding the denominator
limit = power(10, precision-1);
while (frac(num) != 0 && max(num, den) < limit) {
  num *= 10;
  den *= 10;
}
num = round(num); den = round(den);

// Simplify the fraction (Euclidean GCD algorithm)
a = num; b = den;
while (b != 0) {
  tmp = b;
  b = a mod b;
  a = tmp;
}
num /= a; den /= a;

// Return a string representing the fraction
if (den == 1)
  return string(num);
else
  return string(num) + "/" + string(den);

Categories: Mathematics

Comments

There are no comments to display.

Post a Comment

You must be signed in to post comments.

Advertisement