Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do you turn a decimal into a fraction (if possible)?

Asked by 6 years ago

I'm trying to calculate ERA for my baseball game, which is:

(number of earned runs allowed / innings pitched) * 9

The issue comes with innings pitched. IP is calculated is thirds of an inning and i can't get a decimal to do this. Is there a way to make a decimal a fraction?

0
Sorry, what couldn't you get a decimal to do? GoldAngelInDisguise 297 — 6y
0
let's say the decimal is 7.2. That would be 7 and 2/3 but it goes as 7 and 2/10. I don't want this. DeceptiveCaster 3761 — 6y
0
Maybe you want to use a base 3 float. You will need a base changing function for that. GoldAngelInDisguise 297 — 6y
0
I updated it to your actual problem. zafiruatest 75 — 6y
0
Tbh I probably should have used my main account. Oh well lol. zafiruatest 75 — 6y

1 answer

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago
local n = 7.2;

local function convert (number)
    local length = tostring(number):len();
    local x = number;
    local y = 1;
    local a = "1";

    for i = 1, length do
        a = a .. "0";
    end

    a = tonumber(a);

    x = x * a;
    y = y * a;

    for i = x, 1, -1 do
       local c = x / i;
       local d = y / i;

       if (c == math.floor(c) and d == math.floor(d)) then
           return c, d;
       end
    end
end

local function convertToWhole (x, y)
    local total = 0;
    local x = x;

    for i = x, 1, -1 do
        if x >= y then
            x = x - y;
            total = total + 1;
        end;
    end
    local a = total;
    local b = x;
    local c = y;
    return a, b, c;
end;

local a, b, c = convertToWhole(convert(n));
print(string.format("%d   %d / %d", a, b, c));
Ad

Answer this question