When trying to print division, it converts fractions to decimals

337 views Asked by At

I am coding a calculator and I was trying to print the division equation's answer, but instead it converted fractions to decimals. I am running Lua 5.2.4

 print ("\n\tWhat math symbol will you use?") 
      ms = io.read()

-- Main function
 function TYPCALC() 

        --If user typed certain math symbols
  if (ms == "division") then

      print ("\n\tWhat number will be divided to?")
          local rn = io.read()

      print ("\n\tWhat will be dividing?")
          local ln = io.read()

          --convert users answers in to strings
          local cln = tonumber(ln)
          local crn = tonumber(rn)

          --do equasion
          io.write (ln / rn)
       end;         

  end ;

    TYPCALC()
2

There are 2 answers

2
Piglet On

Lua does not have a fraction type. You'll have to calculate the numerator and denominator yourself. Then print it.

If you just print or write (number/number2) that expression will be evaluated first, resulting in a decimal number. The function will use a local copy of that number then.

local denominator = 12 -- or some calculated value in your case
local numerator = 1

print(numerator .. "/" .. denominator)

will print 1/12

Another remark:

--convert users answers in to strings
local cln = tonumber(ln)
local crn = tonumber(rn)

If you want to convert a number to a string, you have to use tostring(), not tonumber()

2
robotbeta05 On

I fixed my bug, it turns out that I had to switch the variables places to do the division. Normally you should not have to do this for equations in Lua, but I had to. I ran into this same problem with subtraction, and it fixed that too. Thanks for everyone's help. Here is my change:

io.write (ln / rn)

to

io.write (rn / ln)