How would I go about making a number to Roman numeral converter?

I roughly know how to translate numbers into Roman numerals, but I need some guidance on how I could program user input, which is then converted into Roman numerals. Would I use tables? Would I need to use loops?

4 Likes

You would need a list of Roman numerals with their corresponding number.

I’ve written up some code that’ll do what you want below.
As for the user input part, that won’t be too hard I’m pretty sure you could do that yourself.

numberMap = {
    {1000, 'M'},
    {900, 'CM'},
    {500, 'D'},
    {400, 'CD'},
    {100, 'C'},
    {90, 'XC'},
    {50, 'L'},
    {40, 'XL'},
    {10, 'X'},
    {9, 'IX'},
    {5, 'V'},
    {4, 'IV'},
    {1, 'I'}
    
}

function intToRoman(num)
    local roman = ""
    while num > 0 do
        for index,v in pairs(numberMap)do 
            local romanChar = v[2]
            local int = v[1]
            while num >= int do
                roman = roman..romanChar
                num = num - int
            end
        end
    end
    return roman
end

print("Roman: "..intToRoman(500))
22 Likes

Yes this is a lot more simpler than I expected! Thank you!

2 Likes

I know it’s been 4 years, but is there any way to turn roman numerals to numbers?

Oh wow! I remember posting this during my university days haha. Definitely improved my coding skills since then. But here’s what I got, I found something online and tried it in studio and works like a charm up until 4000.

local map = { 
	I = 1,
	V = 5,
	X = 10,
	L = 50,
	C = 100, 
	D = 500, 
	M = 1000,
}
local numbers = { 1, 5, 10, 50, 100, 500, 1000 }
local chars = { "I", "V", "X", "L", "C", "D", "M" }

local romanToNumber = function(S)
	s = s:upper()
	local ret = 0
	local i = 1
	while i <= s:len() do
		--for i = 1, s:len() do
		local c = s:sub(i, i)
		if c ~= " " then -- allow spaces
			local m = map[c] or error("Unknown Roman Numeral '" .. c .. "'")

			local next = s:sub(i + 1, i + 1)
			local nextm = map[next]

			if next and nextm then
				if nextm > m then 
					-- if string[i] < string[i + 1] then result += string[i + 1] - string[i]
					-- This is used instead of programming in IV = 4, IX = 9, etc, because it is
					-- more flexible and possibly more efficient
					ret = ret + (nextm - m)
					i = i + 1
				else
					ret = ret + m
				end
			else
				ret = ret + m
			end
		end
		i = i + 1
	end
	return ret
end

print(romanToNumber("MMMCMXCIX"))
6 Likes