Behold The Number to Roman Numeral Converter
📆 2026-05-14 15:33
Yesterday, my 9 years old daughter asked me about roman numerals. After a "fun chat" and a small bash script she kind of understood roman numerals. I was left with the bash script so, today, I made a "gemtext" version and put it on my capsule in the "Fun stuff with CGI" [1] section.
The script converts regular numbers into Roman numerals [2]. It takes a normal number (integer) as input and builds the matching Roman numeral by repeatedly subtracting the largest possible values, such as M, CM, XC, or IV. This is called the greedy algorithm [3] because it always grabs the largest valid symbol first.
Check out the online version and see the code at:
🏛 Roman Numeral Converter
How it works
Steps taken in the loop to convert 2994:
- 2994 >= 1000 => add M, subtract 1000 = 1994
- 1994 >= 1000 => add M, subtract 1000 = 994
- 994 >= 900 => add CM, subtract 900 = 94
- 94 >= 90 => add XC, subtract 90 = 4
- 4 >= 4 => add IV, subtract 4 = 0
Result
The magic is in the loop
# Arrays of values and corresponding Roman numerals
# 1000 = M ; 900 = CM etc.
values=(1000 900 500 400 100 90 50 40 10 9 5 4 1)
numerals=("M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX" "V" "IV" "I")
for i in "${!values[@]}"; do
while [ "$number" -ge "${values[$i]}" ]; do
result+="${numerals[$i]}"
((number -= values[$i]))
done
done
This loop goes through each Roman numeral value from largest to smallest. For every value, it checks whether the current number is greater than or equal to that value. If it is, the matching Roman numeral is added to the result string, and that value is subtracted from the number. The process repeats until the number is too small for that value, then moves on to the next smaller one, continuing until it reaches 0. Now the roman numeral is fully converted.
Links
[1] 🪛 Fun Stuff with CGI
[2] Roman numerals on Wikipedia
[3] Greeedy Algorithm on Wikipedia
🚶 Back to my blog