local function FindFraction(float)
local i,f = math.modf(float)
local result = 1 / f % 1 == 0 and '1 / ' .. math.floor(1 / f) or f == 0 and i or nil
if not result then
for k = 1, 10000 do
if 1 / f * k % 1 == 0 then
result = tostring(k + i .. ' / ' .. 1 / f * k)
break
end
end
end
return float > 1 and i .. ' + (' .. result .. ')' or result
end
print(FindFraction(0.1)) -- 1 / 10
print(FindFraction(0.2)) -- 1 / 5
print(FindFraction(0.3)) -- 3 / 10
print(FindFraction(0.4)) -- 2 / 5
print(FindFraction(0.5)) -- 1 / 2
print(FindFraction(0.6)) -- 3 / 5
print(FindFraction(0.7)) -- 7 / 10
print(FindFraction(0.8)) -- 8 / 10
print(FindFraction(0.9)) -- 9 / 10
print(FindFraction(1)) -- 1
print(FindFraction(1.1)) -- nil or error ( what is wrong here? )
it works well sometimes like .234 is 117 / 500 but sometimes it straight errors because the result is nil
tried everything i could, nothing helped
Edit: thanks guys i just found out the problem and solved it by adding f = tonumber(string.format('%g',string.format('%.'..(10)..'f',f))) on the 3rd line!