Roman numerals/Encode: Difference between revisions

m
→‎{{header|Phix}}: use pygments, added cheat version
m (→‎{{header|Phix}}: use pygments, added cheat version)
 
(45 intermediate revisions by 21 users not shown)
Line 16:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V anums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
V rnums = ‘M CM D CD C XC L XL X IX V IV I’.split(‘ ’)
 
Line 30:
1009, 1444, 1666, 1945, 1997, 1999, 2000, 2008, 2010, 2011, 2500, 3000, 3999]
L(val) test
print(val‘ - ’to_roman(val))</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Roman numerals Encode - 11/05/2020
ROMAENC CSECT
USING ROMAENC,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,=A(8)) do i=1 to hbound(nums)
LR R1,R6 i
SLA R1,1 ~
LH R8,NUMS-2(R1) n=nums(i)
MVC PG,=CL80'.... :' clear buffer
LA R9,PG @pg
XDECO R8,XDEC edit n
MVC 0(4,R9),XDEC+8 output n
LA R9,7(R9) @pg+=7
LA R7,1 j=1
DO WHILE=(C,R7,LE,=A(13)) do j=1 to 13
LR R1,R7 j
SLA R1,1 ~
LH R3,ARABIC-2(R1) aj=arabic(j)
DO WHILE=(CR,R8,GE,R3) while n>=aj
LR R1,R7 j
SLA R1,1 ~
LA R4,ROMAN-2(R1) roman(j)
MVC 0(2,R9),0(R4) output roman(j)
IF CLI,1(R9),NE,C' ' THEN if roman(j)[2]=' ' then
LA R9,2(R9) @pg+=2
ELSE , else
LA R9,1(R9) @pg+=1
ENDIF , endif
SR R8,R3 n-=aj
ENDDO , endwile
LA R7,1(R7) j++
ENDDO , enddo j
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling save
ARABIC DC H'1000',H'900',H'500',H'400',H'100',H'90'
DC H'50',H'40',H'10',H'9',H'5',H'4',H'1'
ROMAN DC CL2'M',CL2'CM',CL2'D',CL2'CD',CL2'C',CL2'XC'
DC CL2'L',CL2'XL',CL2'X',CL2'IX',CL2'V',CL2'IV',CL2'I'
NUMS DC H'14',H'16',H'21',H'888',H'1492',H'1999',H'2020',H'3999'
PG DS CL80 buffer
XDEC DS CL12 temp for xdeco
REGEQU
END ROMAENC</syntaxhighlight>
{{out}}
<pre>
14 : XIV
16 : XVI
21 : XXI
888 : DCCCLXXXVIII
1492 : MCDXCII
1999 : MCMXCIX
2020 : MMXX
3999 : MMMCMXCIX
</pre>
 
=={{header|8080 Assembly}}==
<langsyntaxhighlight lang="8080asm"> org 100h
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 131 ⟶ 196:
dgtbufdef: db 5,0
dgtbuf: ds 6
romanbuf:</langsyntaxhighlight>
 
=={{header|8086 Assembly}}==
===Main and Supporting Functions===
The main program and test values: 70,1776,2021,3999,4000
<langsyntaxhighlight lang="asm"> mov ax,0070h
call EncodeRoman
mov si,offset StringRam
Line 164 ⟶ 230:
 
ReturnToDos ;macro that calls the int that exits dos</langsyntaxhighlight>
 
The <code>EncodeRoman</code> routine:
<langsyntaxhighlight lang="asm">;ROMAN NUMERALS MODULE
 
EncodeRoman:
Line 340 ⟶ 406:
ror al,cl ;AX = 0X0Yh
pop cx
ret</langsyntaxhighlight>
 
Macros used:
<langsyntaxhighlight lang="asm">pushall macro
push ax
push bx
Line 362 ⟶ 428:
pop bx
pop ax
endm</langsyntaxhighlight>
===Output===
{{out}}
Line 374 ⟶ 440:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE PTR="CARD"
CARD ARRAY arabic=[1000 900 500 400 100 90 50 40 10 9 5 4 1]
PTR ARRAY roman(13)
Line 413 ⟶ 479:
PrintF("%U=%S%E",data(i),r)
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Roman_numerals_encode.png Screenshot from Atari 8-bit computer]
Line 426 ⟶ 492:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function arabic2roman(num:Number):String {
var lookup:Object = {M:1000, CM:900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1};
var roman:String = "", i:String;
Line 440 ⟶ 506:
trace("2008 in roman is " + arabic2roman(2008));
trace("1666 in roman is " + arabic2roman(1666));
</syntaxhighlight>
</lang>
{{out}}
<pre>1990 in roman is MCMXC
Line 447 ⟶ 513:
</pre>
And the reverse:
<langsyntaxhighlight ActionScriptlang="actionscript">function roman2arabic(roman:String):Number {
var romanArr:Array = roman.toUpperCase().split('');
var lookup:Object = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
Line 459 ⟶ 525:
trace("MCMXC in arabic is " + roman2arabic("MCMXC"));
trace("MMVIII in arabic is " + roman2arabic("MMVIII"));
trace("MDCLXVI in arabic is " + roman2arabic("MDCLXVI"));</langsyntaxhighlight>
{{out}}
<pre>MCMXC in arabic is 1990
Line 466 ⟶ 532:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Roman_Numeral_Test is
Line 498 ⟶ 564:
Put_Line (To_Roman (25));
Put_Line (To_Roman (944));
end Roman_Numeral_Test;</langsyntaxhighlight>
{{out}}
<pre>
Line 512 ⟶ 578:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">[]CHAR roman = "MDCLXVmdclxvi"; # UPPERCASE for thousands #
[]CHAR adjust roman = "CCXXmmccxxii";
[]INT arabic = (1000000, 500000, 100000, 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1);
Line 540 ⟶ 606:
print((val, " - ", arabic to roman(val), new line))
OD
)</langsyntaxhighlight>
{{out}} (last example is manually wrapped):
<pre style="height:30ex;overflow:scroll">
Line 641 ⟶ 707:
{{works with|awtoc|any - tested with release [http://www.jampan.co.nz/~glyn/aw2c.tar.gz Mon Apr 27 14:25:27 NZST 2009]}}
<!-- This specimen was emailed to be by Glyn Webster > "Here's a Roman number procedure that would fit in:" -->
<langsyntaxhighlight lang="algolw">BEGIN
 
PROCEDURE ROMAN (INTEGER VALUE NUMBER; STRING(15) RESULT CHARACTERS; INTEGER RESULT LENGTH);
Line 691 ⟶ 757:
ROMAN(2009, S, I); WRITE(S, I);
ROMAN(405, S, I); WRITE(S, I);
END.</langsyntaxhighlight>
{{out}}
<pre>
Line 703 ⟶ 769:
=={{header|APL}}==
{{works with|Dyalog APL}}
<langsyntaxhighlight APLlang="apl">toRoman←{
⍝ Digits and corresponding values
ds←((⊢≠⊃)⊆⊢)' M CM D CD C XC L XL X IX V IV I'
Line 712 ⟶ 778:
(d⊃ds),∇⍵-d⊃vs ⍝ While one exists, add it and subtract from number
}⍵
}</langsyntaxhighlight>
 
{{out}}
Line 724 ⟶ 790:
{{Trans|Haskell}}
(mapAccumL version)
<langsyntaxhighlight AppleScriptlang="applescript">------------------ ROMAN INTEGER STRINGS -----------------
 
-- roman :: Int -> String
Line 860 ⟶ 926:
missing value
end if
end snd</langsyntaxhighlight>
{{Out}}
<pre>{"MMXVI", "MCMXC", "MMVIII", "MM", "MDCLXVI"}</pre>
Line 866 ⟶ 932:
=={{header|Arturo}}==
{{trans|Nim}}
<langsyntaxhighlight lang="rebol">nums: [[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"])
Line 892 ⟶ 958:
1000 1009 1444 1666 1945 1997 1999 2000 2008 2010 2011 2500
3000 3999] 'n
-> print [n "->" toRoman n]</langsyntaxhighlight>
 
{{out}}
Line 953 ⟶ 1,019:
=={{header|AutoHotkey}}==
{{trans|C++}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % stor(444)
 
stor(value)
Line 980 ⟶ 1,046:
}
Return result . "O"
}</langsyntaxhighlight>
 
=={{header|Autolisp}}==
<syntaxhighlight lang="autolisp">
<lang Autolisp>
(defun c:roman() (romanNumber (getint "\n Enter number > "))
(defun romanNumber (n / uni dec hun tho nstr strlist nlist rom)
Line 1,008 ⟶ 1,074:
rom
)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,018 ⟶ 1,084:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f ROMAN_NUMERALS_ENCODE.AWK
BEGIN {
Line 1,045 ⟶ 1,111:
return(roman1000[v] roman100[w] roman10[x] roman1[y])
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,054 ⟶ 1,120:
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic"> 1 N = 1990: GOSUB 5: PRINT N" = "V$
2 N = 2008: GOSUB 5: PRINT N" = "V$
3 N = 1666: GOSUB 5: PRINT N" = "V$;
4 END
5 V = N:V$ = "": FOR I = 0 TO 12: FOR L = 1 TO 0 STEP 0:A = VAL ( MID$ ("1E3900500400100+90+50+40+10+09+05+04+01",I * 3 + 1,3))
6 L = (V - A) > = 0:V$ = V$ + MID$ ("M.CMD.CDC.XCL.XLX.IXV.IVI",I * 2 + 1,(I - INT (I / 2) * 2 + 1) * L):V = V - A * L: NEXT L,I
7 RETURN</syntaxhighlight>
 
==={{header|ASIC}}===
{{trans|DWScript}}
<langsyntaxhighlight lang="basic">
REM Roman numerals/Encode
DIM Weights(12)
Line 1,098 ⟶ 1,173:
ExitToRoman:
RETURN
</syntaxhighlight>
</lang>
 
==={{header|BaCon}}===
<syntaxhighlight lang="bacon">OPTION BASE 1
 
GLOBAL roman$[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }
GLOBAL number[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
 
FUNCTION toroman$(value)
 
LOCAL result$
 
DOTIMES UBOUND(number)
WHILE value >= number[_]
result$ = result$ & roman$[_]
DECR value, number[_]
WEND
DONE
 
RETURN result$
 
ENDFUNC
 
PRINT toroman$(1990)
PRINT toroman$(2008)
PRINT toroman$(1666)
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMVIII
MDCLXVI
</pre>
 
==={{header|BASIC256}}===
{{works with|BASIC256 }}
<syntaxhighlight lang="basic256">
print 1666+" = "+convert$(1666)
print 2008+" = "+convert$(2008)
print 1001+" = "+convert$(1001)
print 1999+" = "+convert$(1999)
 
function convert$(value)
convert$=""
arabic = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
roman$ = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
for i = 0 to 12
while value >= arabic[i]
convert$ += roman$[i]
value = value - arabic[i]
end while
next i
end function
</syntaxhighlight>
{{out}}
<pre>
1666 = MDCLXVI
2008 = MMVIII
1001 = MI
1999 = MCMXCIX
</pre>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> PRINT ;1999, FNroman(1999)
PRINT ;2012, FNroman(2012)
PRINT ;1666, FNroman(1666)
PRINT ;3888, FNroman(3888)
END
DEF FNroman(n%)
LOCAL i%, r$, arabic%(), roman$()
DIM arabic%(12), roman$(12)
arabic%() = 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900,1000
roman$() = "I","IV", "V","IX", "X","XL", "L","XC", "C","CD", "D","CM", "M"
FOR i% = 12 TO 0 STEP -1
WHILE n% >= arabic%(i%)
r$ += roman$(i%)
n% -= arabic%(i%)
ENDWHILE
NEXT
= r$</syntaxhighlight>
{{out}}
<pre>
1999 MCMXCIX
2012 MMXII
1666 MDCLXVI
3888 MMMDCCCLXXXVIII
</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|GW-BASIC}}
<syntaxhighlight lang="qbasic">100 cls
110 dim arabic(12), roman$(12)
120 for j = 0 to 12 : read arabic(j),roman$(j) : next j
130 data 1000,"M", 900,"CM", 500,"D", 400,"CD", 100,"C", 90,"XC"
140 data 50,"L",40,"XL",10,"X",9,"IX",5,"V",4,"IV",1,"I"
187 avalor = 1990 : print avalor "= "; : gosub 220 : print roman$ ' MCMXC
188 avalor = 2008 : print avalor "= "; : gosub 220 : print roman$ ' MMXXII
189 avalor = 1666 : print avalor "= "; : gosub 220 : print roman$ ' MDCLXVI
200 end
210 rem Encode to Roman
220 roman$ = "" : i = 0
230 while (i <= 12) and (avalor > 0)
240 while avalor >= arabic(i)
250 roman$ = roman$+roman$(i)
260 avalor = avalor-arabic(i)
270 wend
280 i = i+1
290 wend
300 return</syntaxhighlight>
{{out}}
<pre>1990 = MCMXC
2008 = MMVIII
1666 = MDCLXVI</pre>
 
==={{header|Commodore BASIC}}===
{{works with|Commodore BASIC|7.0}}
C-128 version:
<langsyntaxhighlight lang="basic">100 DIM RN$(12),NV(12)
110 FOR I=0 TO 12
120 : READ RN$(I), NV(I)
Line 1,128 ⟶ 1,317:
330 : LOOP
340 : PRINT RN$;CHR$(13)
350 LOOP</langsyntaxhighlight>
 
{{works with|Commodore BASIC|3.5}}
C-16/116/Plus-4 version (BASIC 3.5 has DO/LOOP but not BEGIN/BEND)
<langsyntaxhighlight lang="basic">100 DIM RN$(12),NV(12)
110 FOR I=0 TO 12
120 : READ RN$(I), NV(I)
Line 1,156 ⟶ 1,345:
330 : LOOP
340 : PRINT RN$;CHR$(13)
350 LOOP</langsyntaxhighlight>
 
{{works with|Commodore BASIC|2.0}}
This version works on any Commodore, though the title banner should be adjusted to match the color and screen width of the particular machine.
<langsyntaxhighlight lang="basic">100 DIM RN$(12),NV(12)
110 FOR I=0 TO 12
120 : READ RN$(I), NV(I)
Line 1,185 ⟶ 1,374:
340 : PRINT RN$;CHR$(13)
350 GOTO 210
</syntaxhighlight>
</lang>
 
The output is the same for all the above versions:
Line 1,206 ⟶ 1,395:
==={{header|FreeBASIC}}===
{{works with|FreeBASIC}}
<langsyntaxhighlight lang="freebasic">
DIM SHARED arabic(0 TO 12) AS Integer => {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
DIM SHARED roman(0 TO 12) AS String*2 => {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
Line 1,227 ⟶ 1,416:
PRINT "1666 = "; toRoman(1666)
PRINT "3888 = "; toRoman(3888)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,234 ⟶ 1,423:
1666 = MDCLXVI
3888 = MMMDCCCLXXXVIII
</pre>
 
Another solution:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function romanEncode(n As Integer) As String
If n < 1 OrElse n > 3999 Then Return "" '' can only encode numbers in range 1 to 3999
Dim roman1(0 To 2) As String = {"MMM", "MM", "M"}
Dim roman2(0 To 8) As String = {"CM", "DCCC", "DCC", "DC", "D", "CD", "CCC", "CC", "C"}
Dim roman3(0 To 8) As String = {"XC", "LXXX", "LXX", "LX", "L", "XL", "XXX", "XX", "X"}
Dim roman4(0 To 8) As String = {"IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I"}
Dim As Integer thousands, hundreds, tens, units
thousands = n \ 1000
n Mod= 1000
hundreds = n \ 100
n Mod= 100
tens = n \ 10
units = n Mod 10
Dim roman As String = ""
If thousands > 0 Then roman += roman1(3 - thousands)
If hundreds > 0 Then roman += roman2(9 - hundreds)
If tens > 0 Then roman += roman3(9 - tens)
If units > 0 Then roman += roman4(9 - units)
Return roman
End Function
 
Dim a(2) As Integer = {1990, 2008, 1666}
For i As Integer = 0 To 2
Print a(i); " => "; romanEncode(a(i))
Next
 
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
1990 => MCMXC
2008 => MMVIII
1666 => MDCLXVI
</pre>
 
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">window 1
 
local fn DecimaltoRoman( decimal as short ) as Str15
short arabic(12)
Str15 roman(12)
long i
Str15 result : result = ""
arabic(0) = 1000 : arabic(1) = 900 : arabic(2) = 500 : arabic(3) = 400
arabic(4) = 100 : arabic(5) = 90 : arabic(6) = 50 : arabic(7) = 40
arabic(8) = 10 : arabic(9) = 9 : arabic(10) = 5 : arabic(11) = 4: arabic(12) = 1
roman(0) = "M" : roman(1) = "CM" : roman(2) = "D" : roman(3) = "CD"
roman(4) = "C" : roman(5) = "XC" : roman(6) = "L" : roman(7) = "XL"
roman(8) = "X" : roman(9) = "IX" : roman(10) = "V" : roman(11) = "IV" : roman(12) = "I"
for i = 0 to 12
while ( decimal >= arabic(i) )
result = result + roman(i)
decimal = decimal - arabic(i)
wend
next i
if result == "" then result = "Zepherium"
end fn = result
 
print "1990 = "; fn DecimaltoRoman( 1990 )
print "2008 = "; fn DecimaltoRoman( 2008 )
print "2016 = "; fn DecimaltoRoman( 2016 )
print "1666 = "; fn DecimaltoRoman( 1666 )
print "3888 = "; fn DecimaltoRoman( 3888 )
print "1914 = "; fn DecimaltoRoman( 1914 )
print "1000 = "; fn DecimaltoRoman( 1000 )
print " 513 = "; fn DecimaltoRoman( 513 )
print " 33 = "; fn DecimaltoRoman( 33 )
 
HandleEvents</syntaxhighlight>
 
Output:
<pre>
1990 = MCMXC
2008 = MMVIII
2016 = MMXVI
1666 = MDCLXVI
3888 = MMMDCCCLXXXVIII
1914 = MCMXIV
1000 = M
513 = DXIII
33 = XXXIII
</pre>
 
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
'Testing
Print "2009 = "; toRoman(2009)
Print "1666 = "; toRoman(1666)
Print "3888 = "; toRoman(3888)
 
End
 
Function toRoman(value As Integer) As String
 
Dim result As String
Dim arabic As Integer[] = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
Dim roman As String[] = ["M", "CM", "D", "CD", "C", "XC", "L" , "XL", "X", "IX", "V", "IV", "I"]
 
For i As Integer = 0 To arabic.Max
Do While value >= arabic[i]
result &= roman[i]
value -= arabic[i]
Loop
Next
Return result
 
End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=== {{header|GW-BASIC}} ===
{{trans|DWScript}}
{{works with|BASICA}}
<syntaxhighlight lang="gwbasic">
10 REM Roman numerals/Encode
20 DIM WEIGHTS%(12), SYMBOLS$(12)
30 FOR J% = 0 TO 12: READ WEIGHTS%(J%), SYMBOLS$(J%): NEXT J%
40 DATA 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC"
50 DATA 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V", 4, "IV", 1, "I"
60 REM 3888 or MMMDCCCLXXXVIII (15 chars) is
70 REM the longest string properly encoded
80 REM with these symbols.
90 AVALUE% = 1990: GOSUB 1000: PRINT ROMAN$ ' MCMXC
100 AVALUE% = 2022: GOSUB 1000: PRINT ROMAN$ ' MMXXII
110 AVALUE% = 3888: GOSUB 1000: PRINT ROMAN$ ' MMMDCCCLXXXVIII
120 END
990 REM Encode to roman
1000 ROMAN$ = "": I% = 0
1010 WHILE (I% <= 12) AND (AVALUE% > 0)
1020 WHILE AVALUE% >= WEIGHTS%(I%)
1030 ROMAN$ = ROMAN$ + SYMBOLS$(I%)
1040 AVALUE% = AVALUE% - WEIGHTS%(I%)
1050 WEND
1060 I% = I% + 1
1070 WEND
1080 RETURN
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMXXII
MMMDCCCLXXXVIII
</pre>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Roman.bas"
110 DO
120 PRINT :INPUT PROMPT "Enter an arabic number: ":N
Line 1,260 ⟶ 1,604:
310 END DEF
320 DATA 1000,"M",900,"CM",500,"D",400,"CD",100,"C",90,"XC"
330 DATA 50,"L",40,"XL",10,"X",9,"IX",5,"V",4,"IV",1,"I"</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">
dim arabic( 12)
for i =0 to 12
read k
arabic( i) =k
next i
data 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
 
dim roman$( 12)
for i =0 to 12
read k$
roman$( i) =k$
next i
data "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
 
print 2009, toRoman$( 2009)
print 1666, toRoman$( 1666)
print 3888, toRoman$( 3888)
 
end
 
function toRoman$( value)
i =0
result$ =""
for i = 0 to 12
while value >=arabic( i)
result$ = result$ + roman$( i)
value = value - arabic( i)
wend
next i
toRoman$ =result$
end function
</syntaxhighlight>
<pre>
2009 MMIX
1666 MDCLXVI
3888 MMMDCCCLXXXVIII
</pre>
 
==={{header|Microsoft Small Basic}}===
{{trans|DWScript}}
<syntaxhighlight lang="microsoftsmallbasic">
arabicNumeral = 1990
ConvertToRoman()
TextWindow.WriteLine(romanNumeral) 'MCMXC
arabicNumeral = 2018
ConvertToRoman()
TextWindow.WriteLine(romanNumeral) 'MMXVIII
arabicNumeral = 3888
ConvertToRoman()
TextWindow.WriteLine(romanNumeral) 'MMMDCCCLXXXVIII
Sub ConvertToRoman
weights[0] = 1000
weights[1] = 900
weights[2] = 500
weights[3] = 400
weights[4] = 100
weights[5] = 90
weights[6] = 50
weights[7] = 40
weights[8] = 10
weights[9] = 9
weights[10] = 5
weights[11] = 4
weights[12] = 1
symbols[0] = "M"
symbols[1] = "CM"
symbols[2] = "D"
symbols[3] = "CD"
symbols[4] = "C"
symbols[5] = "XC"
symbols[6] = "L"
symbols[7] = "XL"
symbols[8] = "X"
symbols[9] = "IX"
symbols[10] = "V"
symbols[11] = "IV"
symbols[12] = "I"
romanNumeral = ""
i = 0
While (i <= 12) And (arabicNumeral > 0)
While arabicNumeral >= weights[i]
romanNumeral = Text.Append(romanNumeral, symbols[i])
arabicNumeral = arabicNumeral - weights[i]
EndWhile
i = i + 1
EndWhile
EndSub
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMXVIII
MMMDCCCLXXXVIII
</pre>
 
==={{header|Nascom BASIC}}===
{{trans|DWScript}}
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="basic">
10 REM Roman numerals/Encode
20 DIM WEIGHTS(12),SYMBOLS$(12)
30 FOR I=0 TO 12
40 READ WEIGHTS(I),SYMBOLS$(I)
50 NEXT I
60 DATA 1000,M,900,CM,500,D,400,CD,100,C,90,XC
70 DATA 50,L,40,XL,10,X,9,IX,5,V,4,IV,1,I
80 REM ** 3888 or MMMDCCCLXXXVIII (15 chars) is
90 REM the longest string properly encoded
100 REM with these symbols.
110 V=1990:GOSUB 500
120 PRINT ROMAN$:REM MCMXC
130 V=2022:GOSUB 500
140 PRINT ROMAN$:REM MMXXII
150 V=3888:GOSUB 500
160 PRINT ROMAN$:REM MMMDCCCLXXXVIII
170 END
490 REM ** Encode to roman
500 ROMAN$=""
510 I=0
520 IF I>12 OR V<=0 THEN RETURN
530 IF V<WEIGHTS(I) THEN 570
540 ROMAN$=ROMAN$+SYMBOLS$(I)
550 V=V-WEIGHTS(I)
560 GOTO 530
570 I=I+1
580 GOTO 520
590 RETURN
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMXXII
MMMDCCCLXXXVIII
</pre>
 
==={{header|PowerBASIC}}===
{{trans|BASIC}}
{{works with|PB/Win|8+}}
{{works with|PB/CC|5}}
<syntaxhighlight lang="powerbasic">FUNCTION toRoman(value AS INTEGER) AS STRING
DIM arabic(0 TO 12) AS INTEGER
DIM roman(0 TO 12) AS STRING
ARRAY ASSIGN arabic() = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
ARRAY ASSIGN roman() = "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
 
DIM i AS INTEGER
DIM result AS STRING
 
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
result = result & roman(i)
value = value - arabic(i)
LOOP
NEXT i
toRoman = result
END FUNCTION
 
FUNCTION PBMAIN
'Testing
? "2009 = " & toRoman(2009)
? "1666 = " & toRoman(1666)
? "3888 = " & toRoman(3888)
END FUNCTION</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">#SymbolCount = 12 ;0 based count
DataSection
denominations:
Data.s "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" ;0-12
denomValues:
Data.i 1000,900,500,400,100,90,50,40,10,9,5,4,1 ;values in decending sequential order
EndDataSection
 
;-setup
Structure romanNumeral
symbol.s
value.i
EndStructure
Global Dim refRomanNum.romanNumeral(#SymbolCount)
 
Restore denominations
For i = 0 To #SymbolCount
Read.s refRomanNum(i)\symbol
Next
 
Restore denomValues
For i = 0 To #SymbolCount
Read refRomanNum(i)\value
Next
 
Procedure.s decRoman(n)
;converts a decimal number to a roman numeral
Protected roman$, i
For i = 0 To #SymbolCount
Repeat
If n >= refRomanNum(i)\value
roman$ + refRomanNum(i)\symbol
n - refRomanNum(i)\value
Else
Break
EndIf
ForEver
Next
 
ProcedureReturn roman$
EndProcedure
 
If OpenConsole()
 
PrintN(decRoman(1999)) ;MCMXCIX
PrintN(decRoman(1666)) ;MDCLXVI
PrintN(decRoman(25)) ;XXV
PrintN(decRoman(954)) ;CMLIV
 
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</syntaxhighlight>
 
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">DIM SHARED arabic(0 TO 12)
DIM SHARED roman$(0 TO 12)
 
FUNCTION toRoman$ (value)
LET result$ = ""
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
LET result$ = result$ + roman$(i)
LET value = value - arabic(i)
LOOP
NEXT i
toRoman$ = result$
END FUNCTION
 
FOR i = 0 TO 12
READ arabic(i), roman$(i)
NEXT i
 
DATA 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC"
DATA 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V", 4, "IV", 1, "I"
 
'Testing
PRINT "2009 = "; toRoman$(2009)
PRINT "1666 = "; toRoman$(1666)
PRINT "3888 = "; toRoman$(3888)</syntaxhighlight>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">[loop]
input "Input value:";val$
print roman$(val$)
goto [loop]
 
' ------------------------------
' Roman numerals
' ------------------------------
FUNCTION roman$(val$)
a2r$ = "M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1"
v = val(val$)
for i = 1 to 13
r$ = word$(a2r$,i,",")
a = val(word$(r$,2,":"))
while v >= a
roman$ = roman$ + word$(r$,1,":")
v = v - a
wend
next i
END FUNCTION</syntaxhighlight>
 
==={{header|TI-83 BASIC}}===
<syntaxhighlight lang="ti83b">PROGRAM:DEC2ROM
:"="→Str1
:Lbl ST
:ClrHome
:Disp "NUMBER TO"
:Disp "CONVERT:"
:Input A
:If fPart(A) or A≠abs(A)
:Then
:Goto PI
:End
:A→B
:While B≥1000
:Str1+"M"→Str1
:B-1000→B
:End
:If B≥900
:Then
:Str1+"CM"→Str1
:B-900→B
:End
:If B≥500
:Then
:Str1+"D"→Str1
:B-500→B
:End
:If B≥400
:Then
:Str1+"CD"?Str1
:B-400→B
:End
:While B≥100
:Str1+"C"→Str1
:B-100→B
:End
:If B≥90
:Then
:Str1+"XC"→Str1
:B-90→B
:End
:If B≥50
:Then
:Str1+"L"→Str1
:B-50→B
:End
:If B≥40
:Then
:Str1+"XL"→Str1
:B-40→B
:End
:While B≥10
:Str1+"X"→Str1
:B-10→B
:End
:If B≥9
:Then
:Str1+"IX"→Str1
:B-9→B
:End
:If B≥5
:Then
:Str1+"V"→Str1
:B-5→B
:End
:If B≥4
:Then
:Str1+"IV"→Str1
:B-4→B
:End
:While B>0
:Str1+"I"→Str1
:B-1→B
:End
:ClrHome
:Disp A
:Disp Str1
:Stop
:Lbl PI
:ClrHome
:Disp "THE NUMBER MUST"
:Disp "BE A POSITIVE"
:Disp "INTEGER."
:Pause
:Goto ST
</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">OPTION BASE 0
DIM arabic(12), roman$(12)
 
FOR i = 0 to 12
READ arabic(i), roman$(i)
NEXT i
 
DATA 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC"
DATA 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V", 4, "IV", 1, "I"
 
FUNCTION toRoman$(value)
LET result$ = ""
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
LET result$ = result$ & roman$(i)
LET value = value - arabic(i)
LOOP
NEXT i
LET toRoman$ = result$
END FUNCTION
 
!Testing
PRINT "2009 = "; toRoman$(2009)
PRINT "1666 = "; toRoman$(1666)
PRINT "3888 = "; toRoman$(3888)
END</syntaxhighlight>
 
==={{header|uBasic/4tH}}===
{{trans|BBC Basic}}
<syntaxhighlight lang="text">Push 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000
' Initialize array
For i = 12 To 0 Step -1
@(i) = Pop()
Next
' Calculate and print numbers
Print 1999, : Proc _FNroman (1999)
Print 2014, : Proc _FNroman (2014)
Print 1666, : Proc _FNroman (1666)
Print 3888, : Proc _FNroman (3888)
 
End
 
_FNroman Param (1) ' ( n --)
Local (1) ' Define b@
' Try all numbers in array
For b@ = 12 To 0 Step -1
Do While a@ > @(b@) - 1 ' Several occurences of same number?
GoSub ((b@ + 1) * 10) ' Print roman digit
a@ = a@ - @(b@) ' Decrement number
Loop
Next
 
Print ' Terminate line
Return
' Print roman digits
10 Print "I"; : Return
20 Print "IV"; : Return
30 Print "V"; : Return
40 Print "IX"; : Return
50 Print "X"; : Return
60 Print "XL"; : Return
70 Print "L"; : Return
80 Print "XC"; : Return
90 Print "C"; : Return
100 Print "CD"; : Return
110 Print "D"; : Return
120 Print "CM"; : Return
130 Print "M"; : Return</syntaxhighlight>
 
==={{header|Visual Basic}}===
{{trans|BASIC}}
 
<syntaxhighlight lang="vb">Function toRoman(value) As String
Dim arabic As Variant
Dim roman As Variant
 
arabic = Array(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
roman = Array("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
 
Dim i As Integer, result As String
 
For i = 0 To 12
Do While value >= arabic(i)
result = result + roman(i)
value = value - arabic(i)
Loop
Next i
 
toRoman = result
End Function
 
Sub Main()
MsgBox toRoman(Val(InputBox("Number, please")))
End Sub</syntaxhighlight>
 
==={{header|XBasic}}===
{{trans|DWScript}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">
PROGRAM "romanenc"
VERSION "0.0000"
 
DECLARE FUNCTION Entry()
INTERNAL FUNCTION ToRoman$(aValue%%)
 
' 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded with these symbols.
 
FUNCTION Entry()
PRINT ToRoman$(1990) ' MCMXC
PRINT ToRoman$(2018) ' MMXVIII
PRINT ToRoman$(3888) ' MMMDCCCLXXXVIII
END FUNCTION
 
FUNCTION ToRoman$(aValue%%)
DIM weights%%[12]
DIM symbols$[12]
 
weights%%[0] = 1000
weights%%[1] = 900
weights%%[2] = 500
weights%%[3] = 400
weights%%[4] = 100
weights%%[5] = 90
weights%%[6] = 50
weights%%[7] = 40
weights%%[8] = 10
weights%%[9] = 9
weights%%[10] = 5
weights%%[11] = 4
weights%%[12] = 1
 
symbols$[0] = "M"
symbols$[1] = "CM"
symbols$[2] = "D"
symbols$[3] = "CD"
symbols$[4] = "C"
symbols$[5] = "XC"
symbols$[6] = "L"
symbols$[7] = "XL"
symbols$[8] = "X"
symbols$[9] = "IX"
symbols$[10] = "V"
symbols$[11] = "IV"
symbols$[12] = "I"
 
destination$ = ""
i@@ = 0
DO WHILE (i@@ <= 12) AND (aValue%% > 0)
DO WHILE aValue%% >= weights%%[i@@]
destination$ = destination$ + symbols$[i@@]
aValue%% = aValue%% - weights%%[i@@]
LOOP
i@@ = i@@ + 1
LOOP
RETURN destination$
END FUNCTION
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMXVIII
MMMDCCCLXXXVIII
</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">roman$ = "M, CM, D, CD, C, XC, L, XL, X, IX, V, IV, I"
decml$ = "1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1"
sub toRoman$(value)
local res$, i, roman$(1), decml$(1), long
long = token(roman$, roman$(), ", ")
long = token(decml$, decml$(), ", ")
for i=1 to long
while(value >= val(decml$(i)))
res$ = res$ + roman$(i)
value = value - val(decml$(i))
wend
next i
return res$
end sub
print 400, " ", toRoman$(400)
print 1990, " ", toRoman$(1990)
print 2008, " ", toRoman$(2008)
print 2009, " ", toRoman$(2009)
print 1666, " ", toRoman$(1666)
print 3888, " ", toRoman$(3888)
//Output:
// 400 = CD
// 1990 = MCMXC
// 2008 = MMVIII
// 2009 = MMIX
// 1666 = MDCLXVI
// 3888 = MMMDCCCLXXXVIII</syntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
<langsyntaxhighlight lang="zxbasic"> 10 DATA 1000,"M",900,"CM"
20 DATA 500,"D",400,"CD"
30 DATA 100,"C",90,"XC"
Line 1,279 ⟶ 2,184:
150 GO TO 120
160 NEXT I
170 PRINT VALUE;"=";V$</langsyntaxhighlight>
 
==={{header|BaCon}}===
<lang bacon>OPTION BASE 1
 
GLOBAL roman$[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }
GLOBAL number[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
 
FUNCTION toroman$(value)
 
LOCAL result$
 
DOTIMES UBOUND(number)
WHILE value >= number[_]
result$ = result$ & roman$[_]
DECR value, number[_]
WEND
DONE
 
RETURN result$
 
ENDFUNC
 
PRINT toroman$(1990)
PRINT toroman$(2008)
PRINT toroman$(1666)
</lang>
{{out}}
<pre>
MCMXC
MMVIII
MDCLXVI
</pre>
 
=={{header|BASIC256}}==
{{works with|BASIC256 }}
<lang basic256>
print 1666+" = "+convert$(1666)
print 2008+" = "+convert$(2008)
print 1001+" = "+convert$(1001)
print 1999+" = "+convert$(1999)
 
function convert$(value)
convert$=""
arabic = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
roman$ = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
for i = 0 to 12
while value >= arabic[i]
convert$ += roman$[i]
value = value - arabic[i]
end while
next i
end function
</lang>
{{out}}
<pre>
1666 = MDCLXVI
2008 = MMVIII
1001 = MI
1999 = MCMXCIX
</pre>
 
=={{header|Batch File}}==
{{trans|BASIC}}
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 1,374 ⟶ 2,219:
set result=!result!!rom%a%!
set /a value-=!arab%a%!
goto add_val</langsyntaxhighlight>
{{Out}}
<pre>2009 = MMIX
1666 = MDCLXVI
3888 = MMMDCCCLXXXVIII</pre>
 
=={{header|BBC BASIC}}==
<lang bbcbasic> PRINT ;1999, FNroman(1999)
PRINT ;2012, FNroman(2012)
PRINT ;1666, FNroman(1666)
PRINT ;3888, FNroman(3888)
END
DEF FNroman(n%)
LOCAL i%, r$, arabic%(), roman$()
DIM arabic%(12), roman$(12)
arabic%() = 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900,1000
roman$() = "I","IV", "V","IX", "X","XL", "L","XC", "C","CD", "D","CM", "M"
FOR i% = 12 TO 0 STEP -1
WHILE n% >= arabic%(i%)
r$ += roman$(i%)
n% -= arabic%(i%)
ENDWHILE
NEXT
= r$</lang>
{{out}}
<pre>
1999 MCMXCIX
2012 MMXII
1666 MDCLXVI
3888 MMMDCCCLXXXVIII
</pre>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let toroman(n, v) = valof
Line 1,449 ⟶ 2,267:
show(3888)
show(2021)
$)</langsyntaxhighlight>
{{out}}
<pre>1666 = MDCLXVI
Line 1,461 ⟶ 2,279:
Reads the number to convert from standard input. No range validation is performed.
 
<langsyntaxhighlight lang="befunge">&>0\0>00p:#v_$ >:#,_ $ @
4-v >5+#:/#<\55+%:5/\5%:
vv_$9+00g+5g\00g8+>5g\00
g>\20p>:10p00g \#v _20gv
> 2+ v^-1g01\g5+8<^ +9 _
IVXLCDM</langsyntaxhighlight>
 
{{out}}
Line 1,474 ⟶ 2,292:
=={{header|BQN}}==
{{trans|APL}}
<langsyntaxhighlight BQNlang="bqn">⟨ToRoman⇐R⟩ ← {
ds ← 1↓¨(¯1+`⊏⊸=)⊸⊔" I IV V IX X XL L XC C CD D CM M"
vs ← 1e3∾˜ ⥊1‿4‿5‿9×⌜˜10⋆↕3
Line 1,481 ⟶ 2,299:
(⊑⟜ds∾·𝕊𝕩-⊑⟜vs) 1-˜⊑vs⍋𝕩
}
}</langsyntaxhighlight>
{{out|Example use}}
<syntaxhighlight lang="text"> ToRoman¨ 1990‿2008‿1666‿2021
⟨ "MCMXC" "MMVIII" "MDCLXVI" "MMXXI" ⟩</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( encode
= indian roman cifr tenfoldroman letter tenfold
. !arg:#?indian
Line 1,535 ⟶ 2,353:
)
)
);</langsyntaxhighlight>
{{out}}
<pre>1990 MCMXC
Line 1,547 ⟶ 2,365:
===Naive solution===
This solution is a smart but does not return the number written as a string.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
 
Line 1,571 ⟶ 2,389:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Enter arabic number:
Line 1,580 ⟶ 2,398:
</pre>
===Not thread-safe===
<langsyntaxhighlight Clang="c">#define _CRT_SECURE_NO_WARNINGS
 
#include <stdio.h>
Line 1,604 ⟶ 2,422:
} digits[] = {
{"M", 1000}, {"CM", 900}, {"D", 500 }, {"CD", 400 },
{"C", 100 }, {"XC", 90 }, {"L", 50 }, {"XL", 40}, {"X", 10},
{"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1 }, {"?", 0}
{"?", 0}
};
 
Line 1,667 ⟶ 2,486:
 
return 0;
}</langsyntaxhighlight>
{{Output}}
<pre>Write given numbers as Roman numerals.
Line 1,690 ⟶ 2,509:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
class Program
{
Line 1,717 ⟶ 2,536:
}
}
}</langsyntaxhighlight>
 
One-liner Mono REPL
<langsyntaxhighlight lang="csharp">
Func<int, string> toRoman = (number) =>
new Dictionary<int, string>
Line 1,738 ⟶ 2,557:
{1, "I"}
}.Aggregate(new string('I', number), (m, _) => m.Replace(new string('I', _.Key), _.Value));
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,757 ⟶ 2,576:
=={{header|C++}}==
===C++ 98===
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
 
Line 1,797 ⟶ 2,616:
std::cout << to_roman(i) << std::endl;
}
}</langsyntaxhighlight>
 
===C++ 11===
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
 
Line 1,831 ⟶ 2,650:
for (int i = 0; i < 2018; i++)
std::cout << i << " --> " << to_roman(i) << std::endl;
}</langsyntaxhighlight>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
class Numeral(shared Character char, shared Integer int) {}
Line 1,878 ⟶ 2,697:
assert (toRoman(1990) == "MCMXC");
assert (toRoman(2008) == "MMVIII");
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
The easiest way is to use the built-in cl-format function
<langsyntaxhighlight Clojurelang="clojure">(def arabic->roman
(partial clojure.pprint/cl-format nil "~@R"))
 
Line 1,888 ⟶ 2,707:
;"CXXIII"
(arabic->roman 99)
;"XCIX"</langsyntaxhighlight>Alternatively:<syntaxhighlight lang Clojure="clojure">(def roman-map
(sorted-map
1 "I", 4 "IV", 5 "V", 9 "IX",
Line 1,904 ⟶ 2,723:
 
(int->roman 1999)
; "MCMXCIX"</langsyntaxhighlight>
 
 
An alternate implementation:
 
<syntaxhighlight lang="clojure">
<lang Clojure>
(defn a2r [a]
(let [rv '(1000 500 100 50 10 5 1)
Line 1,926 ⟶ 2,745:
(and (< a v) (< a l)) (recur a (rest rv) (rest dv) r)
:else (recur (- a l) (rest rv) (rest dv) (str r (rm d) (rm v)))))))))
</syntaxhighlight>
</lang>
 
Usage:
 
<syntaxhighlight lang="clojure">
<lang Clojure>
(a2r 1666)
"MDCLXVI"
Line 1,936 ⟶ 2,755:
(map a2r [1000 1 389 45])
("M" "I" "CCCLXXXIX" "XLV")
</syntaxhighlight>
</lang>
 
An alternate implementation:
 
<syntaxhighlight lang="clojure">
<lang Clojure>
(def roman-map
(sorted-map-by >
Line 1,961 ⟶ 2,780:
(>= v e) (cons roman (a2r v n))
(< v e) (cons roman (a2r v (rest n))))))))
</syntaxhighlight>
</lang>
 
Usage:
 
<syntaxhighlight lang="clojure">
<lang Clojure>
(a2r 1666)
"MDCLXVI"
Line 1,971 ⟶ 2,790:
(map a2r [1000 1 389 45])
("M" "I" "CCCLXXXIX" "XLV")
</syntaxhighlight>
</lang>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">roman = cluster is encode
rep = null
Line 2,020 ⟶ 2,839:
stream$putl(po, int$unparse(test) || " = " || roman$encode(test))
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>1666 = MDCLXVI
Line 2,031 ⟶ 2,850:
=={{header|COBOL}}==
 
<syntaxhighlight lang="cobol">
<lang COBOL>
IDENTIFICATION DIVISION.
PROGRAM-ID. TOROMAN.
Line 2,085 ⟶ 2,904:
end-perform
.
</syntaxhighlight>
</lang>
{{out}} (input was supplied via STDIN)
<pre>
Line 2,105 ⟶ 2,924:
=={{header|CoffeeScript}}==
 
<langsyntaxhighlight lang="coffeescript">
decimal_to_roman = (n) ->
# This should work for any positive integer, although it
Line 2,152 ⟶ 2,971:
else
console.log "error for #{decimal}: #{roman} is wrong"
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun roman-numeral (n)
(format nil "~@R" n))</langsyntaxhighlight>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "argv.coh";
 
Line 2,217 ⟶ 3,036:
print(decimalToRoman(number as uint16, &buffer as [uint8]));
print_nl();
end loop;</langsyntaxhighlight>
 
{{out}}
Line 2,227 ⟶ 3,046:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">string toRoman(int n) pure nothrow
in {
assert(n < 5000);
Line 2,252 ⟶ 3,071:
}
 
void main() {}</langsyntaxhighlight>
 
=={{header|Delphi}}==
{{trans|DWScript}}
<langsyntaxhighlight lang="delphi">program RomanNumeralsEncode;
 
{$APPTYPE CONSOLE}
Line 2,283 ⟶ 3,102:
Writeln(IntegerToRoman(2008)); // MMVIII
Writeln(IntegerToRoman(1666)); // MDCLXVI
end.</langsyntaxhighlight>
 
=={{header|DWScript}}==
{{trans|D}}
<langsyntaxhighlight lang="delphi">const weights = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
 
Line 2,306 ⟶ 3,125:
PrintLn(toRoman(455));
PrintLn(toRoman(3456));
PrintLn(toRoman(2488));</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>values[] = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ]
func$ dec2rom dec .
symbol$[] = [ "M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX" "V" "IV" "I" ]
values[] = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ]
func num2rom num . rom$ .
symbol$[] = [ "M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX" "V" "IV" "I" ]
rom$ = ""
for i range= 1 to len values[]
while numdec >= values[i]
rom$ &= symbol$[i]
num dec -= values[i]
.
.
return rom$
.
callprint num2romdec2rom 1990 r$
print r$dec2rom 2008
print dec2rom 1666
call num2rom 2008 r$
</syntaxhighlight>
print r$
call num2rom 1666 r$
print r$</lang>
 
=={{header|ECL}}==
<langsyntaxhighlight ECLlang="ecl">RomanEncode(UNSIGNED Int) := FUNCTION
SetWeights := [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
SetSymbols := ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
Line 2,353 ⟶ 3,171:
RomanEncode(1990 ); //MCMXC
RomanEncode(2008 ); //MMVIII
RomanEncode(1666); //MDCLXVI</langsyntaxhighlight>
 
=={{header|Eiffel}}==
<langsyntaxhighlight Eiffellang="eiffel">class
APPLICATION
 
Line 2,414 ⟶ 3,232:
Result := rnum
end
end</langsyntaxhighlight>
 
=={{header|Ela}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="ela">open number string math
 
digit x y z k =
Line 2,433 ⟶ 3,251:
| else = digit 'I' 'V' 'X' x
 
map (join "" << toRoman) [1999,25,944]</langsyntaxhighlight>
 
{{out}}
Line 2,440 ⟶ 3,258:
=={{header|Elena}}==
{{trans|C#}}
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'collections;
import system'routines;
import extensions;
Line 2,463 ⟶ 3,281:
extension op
{
toRoman()
= RomanDictionary.accumulate(new StringWriter("I", self), (m,kv => m.replace(new StringWriter("I",kv.Key).Value, kv.Value)));
}
Line 2,472 ⟶ 3,290:
console.printLine("2008 : ", 2008.toRoman());
console.printLine("1666 : ", 1666.toRoman())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,482 ⟶ 3,300:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Roman_numeral do
def encode(0), do: ''
def encode(x) when x >= 1000, do: [?M | encode(x - 1000)]
Line 2,498 ⟶ 3,316:
defp digit(8, x, y, _), do: [y, x, x, x]
defp digit(9, x, _, z), do: [x, z]
end</langsyntaxhighlight>
 
'''Another:'''
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Roman_numeral do
@symbols [ {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'} ]
Line 2,511 ⟶ 3,329:
Enum.join(roman)
end
end</langsyntaxhighlight>
 
'''Test:'''
<langsyntaxhighlight lang="elixir">Enum.each([1990, 2008, 1666], fn n ->
IO.puts "#{n}: #{Roman_numeral.encode(n)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 2,526 ⟶ 3,344:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight lang="lisp">(defun ar2ro (AN)
"Translate from arabic number AN to roman number.
For example, (ar2ro 1666) returns (M D C L X V I)."
Line 2,542 ⟶ 3,360:
((>= AN 4) (cons 'I (cons 'V (ar2ro (- AN 4)))))
((>= AN 1) (cons 'I (ar2ro (- AN 1))))
((= AN 0) nil)))</langsyntaxhighlight>
 
=={{header|Erlang}}==
{{trans|OCaml}}
<langsyntaxhighlight lang="erlang">-module(roman).
-export([to_roman/1]).
 
Line 2,565 ⟶ 3,383:
digit(7, X, Y, _) -> [Y, X, X];
digit(8, X, Y, _) -> [Y, X, X, X];
digit(9, X, _, Z) -> [X, Z].</langsyntaxhighlight>
 
sample:
Line 2,580 ⟶ 3,398:
 
Alternative:
<langsyntaxhighlight lang="erlang">
-module( roman_numerals ).
 
Line 2,601 ⟶ 3,419:
map() -> [{"M",1000}, {"CM",900}, {"D",500}, {"CD",400}, {"C",100}, {"XC",90}, {"L",50}, {"XL",40}, {"X",10}, {"IX",9}, {"V",5}, {"IV",4}, {"I\
",1}].
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,614 ⟶ 3,432:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM ARAB2ROMAN
 
Line 2,640 ⟶ 3,458:
TOROMAN(3888->ANS$) PRINT("3888 = ";ANS$)
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
{{trans|BASIC}}
<langsyntaxhighlight Euphorialang="euphoria">constant arabic = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
constant roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
 
Line 2,661 ⟶ 3,479:
printf(1,"%d = %s\n",{2009,toRoman(2009)})
printf(1,"%d = %s\n",{1666,toRoman(1666)})
printf(1,"%d = %s\n",{3888,toRoman(3888)})</langsyntaxhighlight>
 
{{out}}
Line 2,673 ⟶ 3,491:
Excel can encode numbers in Roman forms in 5 successively concise forms.
These can be indicated from 0 to 4. Type in a cell:
<syntaxhighlight lang="excel">
<lang Excel>
=ROMAN(2013,0)
</syntaxhighlight>
</lang>
 
It becomes:
<syntaxhighlight lang="text">
MMXIII
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let digit x y z = function
1 -> x
| 2 -> x + x
Line 2,710 ⟶ 3,528:
|> List.map (fun n -> roman n)
|> List.iter (printfn "%s")
0</langsyntaxhighlight>
{{out}}
<pre>MCMXC
Line 2,718 ⟶ 3,536:
=={{header|Factor}}==
A roman numeral library ships with Factor.
<langsyntaxhighlight lang="factor">USE: roman
( scratchpad ) 3333 >roman .
"mmmcccxxxiii"</langsyntaxhighlight>
 
Parts of the implementation:
 
<langsyntaxhighlight lang="factor">CONSTANT: roman-digits
{ "m" "cm" "d" "cd" "c" "xc" "l" "xl" "x" "ix" "v" "iv" "i" }
 
Line 2,739 ⟶ 3,557:
roman-values roman-digits [
[ /mod swap ] dip <repetition> concat
] 2map "" concat-as nip ;</langsyntaxhighlight>
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">^$." "
[$999>][1000- "M"]#
$899> [ 900-"CM"]?
Line 2,755 ⟶ 3,573:
$ 4> [ 5- "V"]?
$ 3> [ 4-"IV"]?
[$ ][ 1- "I"]#%</langsyntaxhighlight>
 
=={{header|Fan}}==
<syntaxhighlight lang="fan">**
<lang Fan>**
** converts a number to its roman numeral representation
**
Line 2,795 ⟶ 3,613:
}
 
}</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: vector create ( n -- ) 0 do , loop does> ( n -- ) swap cells + @ execute ;
\ these are ( numerals -- numerals )
: ,I dup c@ C, ; : ,V dup 1 + c@ C, ; : ,X dup 2 + c@ C, ;
Line 2,815 ⟶ 3,633:
1999 roman type \ MCMXCIX
25 roman type \ XXV
944 roman type \ CMXLIV</langsyntaxhighlight>
Alternative implementation
<langsyntaxhighlight lang="forth">create romans 0 , 1 , 5 , 21 , 9 , 2 , 6 , 22 , 86 , 13 ,
does> swap cells + @ ;
 
Line 2,835 ⟶ 3,653:
create (roman) 16 chars allot
 
1999 (roman) >roman type cr</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program roman_numerals
 
implicit none
Line 2,873 ⟶ 3,691:
end function roman
 
end program roman_numerals</langsyntaxhighlight>
{{out}}
Line 2,880 ⟶ 3,698:
MDCLXVI
MMMDCCCLXXXVIII
</pre>
 
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
 
Function romanEncode(n As Integer) As String
If n < 1 OrElse n > 3999 Then Return "" '' can only encode numbers in range 1 to 3999
Dim roman1(0 To 2) As String = {"MMM", "MM", "M"}
Dim roman2(0 To 8) As String = {"CM", "DCCC", "DCC", "DC", "D", "CD", "CCC", "CC", "C"}
Dim roman3(0 To 8) As String = {"XC", "LXXX", "LXX", "LX", "L", "XL", "XXX", "XX", "X"}
Dim roman4(0 To 8) As String = {"IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I"}
Dim As Integer thousands, hundreds, tens, units
thousands = n \ 1000
n Mod= 1000
hundreds = n \ 100
n Mod= 100
tens = n \ 10
units = n Mod 10
Dim roman As String = ""
If thousands > 0 Then roman += roman1(3 - thousands)
If hundreds > 0 Then roman += roman2(9 - hundreds)
If tens > 0 Then roman += roman3(9 - tens)
If units > 0 Then roman += roman4(9 - units)
Return roman
End Function
 
Dim a(2) As Integer = {1990, 2008, 1666}
For i As Integer = 0 To 2
Print a(i); " => "; romanEncode(a(i))
Next
 
Print
Print "Press any key to quit"
Sleep</lang>
 
{{out}}
<pre>
1990 => MCMXC
2008 => MMVIII
1666 => MDCLXVI
</pre>
 
=={{header|FutureBasic}}==
<lang futurebasic>
include "ConsoleWindow"
 
local fn DecimaltoRoman( decimal as short ) as Str15
dim as short arabic(12)
dim as Str15 roman(12)
dim as long i
dim as Str15 result : result = ""
 
arabic(0) = 1000 : arabic(1) = 900 : arabic(2) = 500 : arabic(3) = 400
arabic(4) = 100 : arabic(5) = 90 : arabic(6) = 50 : arabic(7) = 40
arabic(8) = 10 : arabic(9) = 9 : arabic(10) = 5 : arabic(11) = 4: arabic(12) = 1
 
roman(0) = "M" : roman(1) = "CM" : roman(2) = "D" : roman(3) = "CD"
roman(4) = "C" : roman(5) = "XC" : roman(6) = "L" : roman(7) = "XL"
roman(8) = "X" : roman(9) = "IX" : roman(10) = "V" : roman(11) = "IV" : roman(12) = "I"
for i = 0 to 12
while ( decimal >= arabic(i) )
result = result + roman(i)
decimal = decimal - arabic(i)
wend
next i
if result == "" then result = "Zepherium"
end fn = result
 
print "1990 = "; fn DecimaltoRoman( 1990 )
print "2008 = "; fn DecimaltoRoman( 2008 )
print "2016 = "; fn DecimaltoRoman( 2016 )
print "1666 = "; fn DecimaltoRoman( 1666 )
print "3888 = "; fn DecimaltoRoman( 3888 )
print "1914 = "; fn DecimaltoRoman( 1914 )
print "1000 = "; fn DecimaltoRoman( 1000 )
print " 513 = "; fn DecimaltoRoman( 513 )
print " 33 = "; fn DecimaltoRoman( 33 )
</lang>
 
Output:
<pre>
1990 = MCMXC
2008 = MMVIII
2016 = MMXVI
1666 = MDCLXVI
3888 = MMMDCCCLXXXVIII
1914 = MCMXIV
1000 = M
513 = DXIII
33 = XXXIII
</pre>
 
Line 2,977 ⟶ 3,704:
 
If you see boxes in the code below, those are supposed to be the Unicode combining overline (U+0305) and look like {{overline|IVXLCDM}}. Or, if you see overstruck combinations of letters, that's a different font rendering problem. (If you need roman numerals > 3999 reliably, it might best to stick to chiseling them in stone...)
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 3,015 ⟶ 3,742:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,024 ⟶ 3,751:
 
=={{header|Golo}}==
<langsyntaxhighlight lang="golo">#!/usr/bin/env golosh
----
This module takes a decimal integer and converts it to a Roman numeral.
Line 3,082 ⟶ 3,809:
println("2008 == MMVIII? " + (2008: encode() == "MMVIII"))
println("1666 == MDCLXVI? " + (1666: encode() == "MDCLXVI"))
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">symbols = [ 1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40:'XL', 50:'L', 90:'XC', 100:'C', 400:'CD', 500:'D', 900:'CM', 1000:'M' ]
 
def roman(arabic) {
Line 3,112 ⟶ 3,839:
assert roman(1666) == 'MDCLXVI'
assert roman(1990) == 'MCMXC'
assert roman(2008) == 'MMVIII'</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 3,118 ⟶ 3,845:
With an explicit decimal digit representation list:
 
<langsyntaxhighlight lang="haskell">digit :: Char -> Char -> Char -> Integer -> String
digit x y z k =
[[x], [x, x], [x, x, x], [x, y], [y], [y, x], [y, x, x], [y, x, x, x], [x, z]] !!
Line 3,140 ⟶ 3,867:
 
main :: IO ()
main = print $ toRoman <$> [1999, 25, 944]</langsyntaxhighlight>
{{out}}
<pre>["MCMXCIX","XXV","CMXLIV"]</pre>
Line 3,146 ⟶ 3,873:
or, defining '''romanFromInt''' in terms of mapAccumL
 
<langsyntaxhighlight lang="haskell">import Data.Bifunctor (first)
import Data.List (mapAccumL)
import Data.Tuple (swap)
Line 3,163 ⟶ 3,890:
 
main :: IO ()
main = (putStrLn . unlines) (roman <$> [1666, 1990, 2008, 2016, 2018])</langsyntaxhighlight>
{{Out}}
<pre>MDCLXVI
Line 3,173 ⟶ 3,900:
With the Roman patterns abstracted, and in a simple logic programming idiom:
 
<langsyntaxhighlight lang="haskell">
module Main where
 
Line 3,233 ⟶ 3,960:
(if roman == expected then "PASS"
else ("FAIL, expected " ++ (show expected))) ++ ")"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,242 ⟶ 3,969:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">CHARACTER Roman*20
 
CALL RomanNumeral(1990, Roman) ! MCMXC
Line 3,263 ⟶ 3,990:
ENDDO
ENDDO
END</langsyntaxhighlight>
 
=={{header|Hoon}}==
 
Library file (e.g. <code>/lib/rhonda.hoon</code>):
 
<syntaxhighlight lang="hoon">|%
++ parse
|= t=tape ^- @ud
=. t (cass t)
=| result=@ud
|-
?~ t result
?~ t.t (add result (from-numeral i.t))
=+ [a=(from-numeral i.t) b=(from-numeral i.t.t)]
?: (gte a b) $(result (add result a), t t.t)
$(result (sub (add result b) a), t t.t.t)
++ yield
|= n=@ud ^- tape
=| result=tape
=/ values to-numeral
|-
?~ values result
?: (gte n -.i.values)
$(result (weld result +.i.values), n (sub n -.i.values))
$(values t.values)
++ from-numeral
|= c=@t ^- @ud
?: =(c 'i') 1
?: =(c 'v') 5
?: =(c 'x') 10
?: =(c 'l') 50
?: =(c 'c') 100
?: =(c 'd') 500
?: =(c 'm') 1.000
!!
++ to-numeral
^- (list [@ud tape])
:*
[1.000 "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"]
~
==
--</syntaxhighlight>
 
Script file ("generator") (e.g. <code>/gen/roman.hoon</code>):
 
<syntaxhighlight lang="hoon">/+ *roman
:- %say
|= [* [x=$%([%from-roman tape] [%to-roman @ud]) ~] ~]
:- %noun
^- tape
?- -.x
%from-roman "{<(parse +.x)>}"
%to-roman (yield +.x)
==</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link numbers # commas, roman
 
procedure main(arglist)
every x := !arglist do
write(commas(x), " -> ",roman(x)|"*** can't convert to Roman numerals ***")
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn numbers.icn provides roman] as seen below and is based upon a James Gimple SNOBOL4 function.
 
<langsyntaxhighlight Iconlang="icon">procedure roman(n) #: convert integer to Roman numeral
local arabic, result
static equiv
Line 3,287 ⟶ 4,080:
result := map(result,"IVXLCDM","XLCDM**") || equiv[arabic + 1]
if find("*",result) then fail else return result
end</langsyntaxhighlight>
 
{{out}}
Line 3,304 ⟶ 4,097:
INTERCAL outputs numbers as Roman numerals by default, so this is surprisingly trivial for a language that generally tries to make things as difficult as possible. Although you do still have to <i>input</i> the numbers as spelled out digitwise in all caps.
 
<langsyntaxhighlight lang="intercal"> PLEASE WRITE IN .1
DO READ OUT .1
DO GIVE UP</langsyntaxhighlight>
 
{{Out}}
Line 3,319 ⟶ 4,112:
 
{{trans|C#}}
<langsyntaxhighlight Iolang="io">Roman := Object clone do (
nums := list(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
rum := list("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
Line 3,336 ⟶ 4,129:
)
 
Roman numeral(1666) println</langsyntaxhighlight>
 
=={{header|J}}==
<tt>rfd</tt> obtains Roman numerals from decimals.
 
<langsyntaxhighlight lang="j">R1000=. ;L:1 ,{ <@(<;._1);._2]0 :0
C CC CCC CD D DC DCC DCCC CM
X XX XXX XL L LX LXX LXXX XC
Line 3,347 ⟶ 4,140:
)
 
rfd=: ('M' $~ <.@%&1000) , R1000 {::~ 1000&|</langsyntaxhighlight>
 
Explanation: R1000's definition contains rows representing each of 10 different digits in the 100s, 10s and 1s column (the first entry in each row is blank -- each entry is preceded by a space). R1000 itself represents the first 1000 roman numerals (the cartesian product of these three rows of roman numeral "digits" which is constructed so that they are in numeric order. And the first entry -- zero -- is just blank). To convert a number to its roman numeral representation, we will separate the number into the integer part after dividing by 1000 (that's the number of 'M's we need) and the remainder after dividing by 1000 (which will be an index into R1000).
 
For example:<langsyntaxhighlight lang="j"> rfd 1234
MCCXXXIV
rfd 567
DLXVII
rfd 89
LXXXIX</langsyntaxhighlight>
 
Derived from the [[j:Essays/Roman Numerals|J Wiki]]. Further examples of use will be found there.
Line 3,365 ⟶ 4,158:
The conversion function throws an IllegalArgumentException for non-positive numbers, since Java does not have unsigned primitives.
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class RN {
 
enum Numeral {
Line 3,405 ⟶ 4,198:
}
 
}</langsyntaxhighlight>
{{out}}
<pre>1999 = MCMXCIX
Line 3,415 ⟶ 4,208:
at RN.main(RN.java:38)</pre>
{{works with|Java|1.8+}}
<langsyntaxhighlight lang="java5">import java.util.Set;
import java.util.EnumSet;
import java.util.Collections;
Line 3,473 ⟶ 4,266:
LongStream.of(1999, 25, 944).forEach(RomanNumerals::test);
}
}</langsyntaxhighlight>
{{out}}
<pre>1999 = MCMXCIX
Line 3,488 ⟶ 4,281:
 
{{trans|Tcl}}
<langsyntaxhighlight lang="javascript">var roman = {
map: [
1000, 'M', 900, 'CM', 500, 'D', 400, 'CD', 100, 'C', 90, 'XC',
Line 3,505 ⟶ 4,298:
}
 
roman.int_to_roman(1999); // "MCMXCIX"</langsyntaxhighlight>
 
====Functional composition====
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 3,557 ⟶ 4,350:
romanTranscription);
 
})();</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">["MMXVI", "MCMXC", "MMVIII", "XIV.IX.MMXV", "MM", "MDCLXVI"]</langsyntaxhighlight>
 
===ES6===
Line 3,566 ⟶ 4,359:
{{Trans|Haskell}}
(mapAccumL version)
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
// --------------- ROMAN INTEGER STRINGS ---------------
 
// roman :: Int -> String
const roman = n =>
mapAccumL(residue => ([k, v]) =>
([k, v]) => second(
q => 0 < q ? k.repeat(q) : ""
) k.repeat(q)
swap(quotRem(residue)(v)) : ""
)(remQuot(residue)(v))
)(n)(
zip([
Line 3,590 ⟶ 4,383:
.join("");
 
// ---------------------- TEST -----------------------
 
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => (
Line 3,599 ⟶ 4,392:
 
// ---------------- GENERIC FUNCTIONS ----------------
 
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: "Tuple",
"0": a,
"1": b,
length: 2
});
 
 
// mapAccumL :: (acc -> x -> (acc, y)) -> acc ->
Line 3,620 ⟶ 4,403:
const tpl = f(a[0])(x);
 
return Tuple(tpl[0])(
tpl[0],
a[1].concat(tpl[1])
)];
},
Tuple([acc)(, [])]
);
 
 
// quotRemremQuot :: Int -> Int -> (Int, Int)
const quotRemremQuot = m =>
n => Tuple([m % n, Math.trunc(m / n))(];
m % n
);
 
 
Line 3,640 ⟶ 4,422:
// to a function over a tuple.
// f (a, b) -> (a, f(b))
xy => Tuple([xy[0]), f(xy[1])];
f(xy[1])
);
 
 
// swap :: (a, b) -> (b, a)
const swap = ab =>
// The pair ab with its order reversed.
Tuple(ab[1])(
ab[0]
);
 
 
Line 3,660 ⟶ 4,432:
length: Math.min(xs.length, ys.length)
}, (_, i) => [xs[i], ys[i]]);
 
 
// MAIN --
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>MDCLXVI
Line 3,673 ⟶ 4,446:
 
====Declarative====
<langsyntaxhighlight JavaScriptlang="javascript">function toRoman(num) {
return 'I'
.repeat(num)
Line 3,690 ⟶ 4,463:
}
 
console.log(toRoman(1666));</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang JavaScript="javascript">MDCLXVI</langsyntaxhighlight>
 
=={{header|jq}}==
Line 3,708 ⟶ 4,481:
 
===Easy-to-code version===
<langsyntaxhighlight lang="jq">def to_roman_numeral:
def romans:
[100000, "\u2188"],
Line 3,739 ⟶ 4,512:
| .n = .n - $i ) )
| .res
end ;</langsyntaxhighlight>
'''Test Cases'''
<langsyntaxhighlight lang="jq">def testcases: [1668, 1990, 2008, 2020, 4444, 5000, 8999, 39999, 89999, 399999];
 
"Decimal => Roman:",
(testcases[]
| " \(.) => \(to_roman_numeral)" )</langsyntaxhighlight>
{{out}}
<pre>
Line 3,763 ⟶ 4,536:
==="Orders of Magnitude" version===
'''Translated from [[#Julia|Julia]]''' extended to 399,999
<langsyntaxhighlight lang="jq">def digits: tostring | explode | map( [.]|implode|tonumber);
# Non-negative integer to Roman numeral up to 399,999
def to_roman_numeral:
Line 3,782 ⟶ 4,555:
| .rnum
end;
</syntaxhighlight>
</lang>
 
=={{header|Jsish}}==
This covers both Encode (toRoman) and Decode (fromRoman).
 
<langsyntaxhighlight lang="javascript">/* Roman numerals, in Jsish */
var Roman = {
ord: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'],
Line 3,842 ⟶ 4,615:
Roman.toRoman(1666) ==> MDCLXVI
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 3,849 ⟶ 4,622:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Printf
 
function romanencode(n::Integer)
Line 3,882 ⟶ 4,655:
for n in testcases
@printf("%-4i => %s\n", n, romanencode(n))
end</langsyntaxhighlight>
 
{{out}}
Line 3,903 ⟶ 4,676:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">val romanNumerals = mapOf(
1000 to "M",
900 to "CM",
Line 3,938 ⟶ 4,711:
println(encode(1666))
println(encode(2008))
}</langsyntaxhighlight>
 
{{out}}
Line 3,947 ⟶ 4,720:
</pre>
Alternatively:
<langsyntaxhighlight lang="scala">fun Int.toRomanNumeral(): String {
fun digit(k: Int, unit: String, five: String, ten: String): String {
return when (k) {
Line 3,965 ⟶ 4,738:
else -> throw IllegalArgumentException("${this} not in range 0..3999")
}
}</langsyntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define br => '\r'
// encode roman
define encodeRoman(num::integer)::string => {
Line 3,986 ⟶ 4,759:
'2008 in roman is '+encodeRoman(2008)
br
'1666 in roman is '+encodeRoman(1666)</langsyntaxhighlight>
 
=={{header|LaTeX}}==
The macro <code>\Roman</code> is defined for uppercase roman numeral, accepting as ''argument'' a name of an existing counter.
 
<langsyntaxhighlight lang="latex">\documentclass{minimal}
\newcounter{currentyear}
\setcounter{currentyear}{\year}
\begin{document}
Anno Domini \Roman{currentyear}
\end{document}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<lang lb>
dim arabic( 12)
for i =0 to 12
read k
arabic( i) =k
next i
data 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
 
dim roman$( 12)
for i =0 to 12
read k$
roman$( i) =k$
next i
data "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
 
print 2009, toRoman$( 2009)
print 1666, toRoman$( 1666)
print 3888, toRoman$( 3888)
 
end
 
function toRoman$( value)
i =0
result$ =""
for i = 0 to 12
while value >=arabic( i)
result$ = result$ + roman$( i)
value = value - arabic( i)
wend
next i
toRoman$ =result$
end function
</lang>
<pre>
2009 MMIX
1666 MDCLXVI
3888 MMMDCCCLXXXVIII
</pre>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">function toRoman intNum
local roman,numArabic
put "M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I" into romans
Line 4,060 ⟶ 4,793:
end repeat
return cc
end repeatChar</langsyntaxhighlight>
 
Examples
Line 4,069 ⟶ 4,802:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">make "roman.rules [
[1000 M] [900 CM] [500 D] [400 CD]
[ 100 C] [ 90 XC] [ 50 L] [ 40 XL]
Line 4,080 ⟶ 4,813:
if :n < first first :rules [output (roman :n bf :rules :acc)]
output (roman :n - first first :rules :rules word :acc last first :rules)
end</langsyntaxhighlight>
 
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">make "patterns [[?] [? ?] [? ? ?] [? ?2] [?2] [?2 ?] [?2 ? ?] [?2 ? ? ?] [? ?3]]
 
to digit :d :numerals
Line 4,100 ⟶ 4,833:
print roman 1999 ; MCMXCIX
print roman 25 ; XXV
print roman 944 ; CMXLIV</langsyntaxhighlight>
 
=={{header|LOLCODE}}==
<langsyntaxhighlight lang="lolcode">HAI 1.2
I HAS A Romunz ITZ A BUKKIT
Romunz HAS A SRS 0 ITZ "M"
Line 4,152 ⟶ 4,885:
VISIBLE SMOOSH 1666 " = " I IZ Romunize YR 1666 MKAY MKAY
VISIBLE SMOOSH 3888 " = " I IZ Romunize YR 3888 MKAY MKAY
KTHXBYE</langsyntaxhighlight>
 
{{Out}}
Line 4,160 ⟶ 4,893:
 
=={{header|LotusScript}}==
<langsyntaxhighlight lang="lss">
Function toRoman(value) As String
Dim arabic(12) As Integer
Line 4,205 ⟶ 4,938:
End Function
 
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
 
<langsyntaxhighlight lang="lua">romans = {
{1000, "M"},
{900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"},
Line 4,223 ⟶ 4,956:
end
end
print()</langsyntaxhighlight>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`roman',`ifelse(eval($1>=1000),1,`M`'roman(eval($1-1000))',
`ifelse(eval($1>=900),1,`CM`'roman(eval($1-900))',
`ifelse(eval($1>=500),1,`D`'roman(eval($1-500))',
Line 4,240 ⟶ 4,973:
)')')')')')')')')')')')')dnl
dnl
roman(3675)</langsyntaxhighlight>
 
{{out}}
Line 4,248 ⟶ 4,981:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">> for n in [ 1666, 1990, 2008 ] do printf( "%d\t%s\n", n, convert( n, 'roman' ) ) end:
1666 MDCLXVI
1990 MCMXC
2008 MMVIII</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
RomanNumeral is a built-in function in the Wolfram language. Examples:
<langsyntaxhighlight Mathematicalang="mathematica">RomanNumeral[4]
RomanNumeral[99]
RomanNumeral[1337]
RomanNumeral[1666]
RomanNumeral[6889]</langsyntaxhighlight>
gives back:
<pre>IV
Line 4,291 ⟶ 5,024:
=== roman.m ===
 
<syntaxhighlight lang="mercury">
<lang Mercury>
:- module roman.
 
Line 4,344 ⟶ 5,077:
 
:- end_module roman.
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,370 ⟶ 5,103:
Another implementation using an algorithm inspired by [[#Erlang|the Erlang implementation]] could look like this:
 
<syntaxhighlight lang="mercury">
<lang Mercury>
:- module roman2.
 
Line 4,419 ⟶ 5,152:
 
:- end_module roman2.
</syntaxhighlight>
</lang>
 
This implementation calculates the value of the thousands, then the hundreds, then the tens, then the ones. In each case it uses the <code>digit/4</code> function and some tricks with unification to build the appropriate list of characters for the digit and multiplier being targeted.
Line 4,425 ⟶ 5,158:
Its output is identical to that of the previous version.
 
=={{header|Microsoft Small BasicMiranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
{{trans|DWScript}}
main = [ Stdout (show n ++ ": " ++ toroman n ++ "\n")
<lang microsoftsmallbasic>
| n <- [1990, 2008, 1666, 2023]]
arabicNumeral = 1990
 
ConvertToRoman()
toroman :: num->[char]
TextWindow.WriteLine(romanNumeral) 'MCMXC
toroman 0 = ""
arabicNumeral = 2018
toroman n = d ++ toroman (n - v)
ConvertToRoman()
where digits = [("M",1000),("CM",900),("D",500),("CD",400),
TextWindow.WriteLine(romanNumeral) 'MMXVIII
("C",100),("XC",90),("L",50),("XL",40),
arabicNumeral = 3888
("X",10),("IX",9),("V",5),("IV",4),
ConvertToRoman()
("I",1)]
TextWindow.WriteLine(romanNumeral) 'MMMDCCCLXXXVIII
(d, v) = hd [(d,v) | (d,v) <- digits; v <= n]</syntaxhighlight>
Sub ConvertToRoman
weights[0] = 1000
weights[1] = 900
weights[2] = 500
weights[3] = 400
weights[4] = 100
weights[5] = 90
weights[6] = 50
weights[7] = 40
weights[8] = 10
weights[9] = 9
weights[10] = 5
weights[11] = 4
weights[12] = 1
symbols[0] = "M"
symbols[1] = "CM"
symbols[2] = "D"
symbols[3] = "CD"
symbols[4] = "C"
symbols[5] = "XC"
symbols[6] = "L"
symbols[7] = "XL"
symbols[8] = "X"
symbols[9] = "IX"
symbols[10] = "V"
symbols[11] = "IV"
symbols[12] = "I"
romanNumeral = ""
i = 0
While (i <= 12) And (arabicNumeral > 0)
While arabicNumeral >= weights[i]
romanNumeral = Text.Append(romanNumeral, symbols[i])
arabicNumeral = arabicNumeral - weights[i]
EndWhile
i = i + 1
EndWhile
EndSub
</lang>
{{out}}
<pre>1990: MCMXC
2008: MMVIII
MCMXC
1666: MDCLXVI
MMXVIII
2023: MMXXIII</pre>
MMMDCCCLXXXVIII
</pre>
 
=={{header|Modula-2}}==
{{trans|DWScript}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<langsyntaxhighlight lang="modula2">
MODULE RomanNumeralsEncode;
 
Line 4,533 ⟶ 5,227:
ToRoman(3888, Numeral); WriteString(Numeral); WriteLn; (* MMMDCCCLXXXVIII *)
END RomanNumeralsEncode.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,542 ⟶ 5,236:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">TOROMAN(INPUT)
;Converts INPUT into a Roman numeral. INPUT must be an integer between 1 and 3999
;OUTPUT is the string to return
Line 4,555 ⟶ 5,249:
.FOR Q:CURRVAL<$PIECE(ROMANVAL,"^",I) SET OUTPUT=OUTPUT_$PIECE(ROMANNUM,"^",I),CURRVAL=CURRVAL-$PIECE(ROMANVAL,"^",I)
KILL I,CURRVAL
QUIT OUTPUT</langsyntaxhighlight>
{{out}}
<pre>USER>W $$ROMAN^ROSETTA(1666)
Line 4,569 ⟶ 5,263:
 
Another variant
<langsyntaxhighlight MUMPSlang="mumps">TOROMAN(n)
;return empty string if input parameter 'n' is not in 1-3999
Quit:(n'?1.4N)!(n'<4000)!'n ""
Line 4,579 ⟶ 5,273:
. Set x=$Translate(x,"IVX",$Piece("IVX~XLC~CDM~M","~",p-j+1))
. Set r=r_x
Quit r</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils
 
const nums = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"),
Line 4,600 ⟶ 5,294:
1000, 1009, 1444, 1666, 1945, 1997, 1999,
2000, 2008, 2010, 2011, 2500, 3000, 3999]:
echo ($i).align(4), ": ", i.toRoman</langsyntaxhighlight>
 
{{out}}
Line 4,660 ⟶ 5,354:
=={{header|Objeck}}==
{{trans|C sharp}}
<langsyntaxhighlight lang="objeck">
bundle Default {
class Roman {
Line 4,693 ⟶ 5,387:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 4,699 ⟶ 5,393:
With an explicit decimal digit representation list:
 
<langsyntaxhighlight lang="ocaml">let digit x y z = function
1 -> [x]
| 2 -> [x;x]
Line 4,721 ⟶ 5,415:
digit 'X' 'L' 'C' (x / 10) @ to_roman (x mod 10)
else
digit 'I' 'V' 'X' x</langsyntaxhighlight>
 
{{out}}
Line 4,735 ⟶ 5,429:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">[ [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"] ] const: Romans
 
: roman(n)
| r |
StringBuffer new
Romans forEach: r [ while(r first n <=) [ r second << n r first - ->n ] ] ;</langsyntaxhighlight>
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">FUNCTION encodeRoman RETURNS CHAR (
i_i AS INT
):
Line 4,779 ⟶ 5,473:
1666 encodeRoman( 1666 ) SKIP
VIEW-AS ALERT-BOX.
</syntaxhighlight>
</lang>
{{out}}
<pre>---------------------------
Line 4,794 ⟶ 5,488:
=={{header|Oz}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="oz">declare
fun {Digit X Y Z K}
unit([X] [X X] [X X X] [X Y] [Y] [Y X] [Y X X] [Y X X X] [X Z])
Line 4,810 ⟶ 5,504:
end
in
{ForAll {Map [1999 25 944] ToRoman} System.showInfo}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Old-style Roman numerals
<langsyntaxhighlight lang="parigp">oldRoman(n)={
while(n>999999,
n-=1000000;
Line 4,868 ⟶ 5,562:
);
print()
};</langsyntaxhighlight>
 
This simple version of medieval Roman numerals does not handle large numbers.
<langsyntaxhighlight lang="parigp">medievalRoman(n)={
while(n>999,
n-=1000;
Line 4,925 ⟶ 5,619:
);
print()
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 4,932 ⟶ 5,626:
=={{header|Peloton}}==
Roman numbers are built in to Peloton as a particular form of national number. However, for the sake of the task the _RO opcode has been defined.
<langsyntaxhighlight lang="sgml"><@ DEFUDOLITLIT>_RO|__Transformer|<@ DEFKEYPAR>__NationalNumericID|2</@><@ LETRESCS%NNMPAR>...|1</@></@>
 
<@ ENU$$DLSTLITLIT>1990,2008,1,2,64,124,1666,10001|,|
<@ SAYELTLST>...</@> is <@ SAY_ROELTLSTLIT>...|RomanLowerUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanUpperUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanASCII</@>
</@></langsyntaxhighlight>
 
Same code in padded-out, variable-length English dialect
<langsyntaxhighlight lang="sgml"><# DEFINE USERDEFINEDOPCODE LITERAL LITERAL>_RO|__Transformer|<# DEFINE KEYWORD PARAMETER>__NationalNumericID|2</#><# LET RESULT CAST NATIONALNUMBER PARAMETER>...|1</#></#>
 
<# ENUMERATION LAMBDASPECIFIEDDELMITER LIST LITERAL LITERAL>1990,2008,1,2,64,124,1666,10001|,|
<# SAY ELEMENT LIST>...</#> is <# SAY _RO ELEMENT LIST LITERAL>...|RomanLowerUnicode</#> <# SAY _RO ELEMENT LIST LITERAL>...|RomanUpperUnicode</#> <# SAY _RO ELEMENT LIST LITERAL>...|RomanASCII</#>
</#></langsyntaxhighlight>
 
{{out}} Notice here the three different ways of representing the results.
Line 4,959 ⟶ 5,653:
==== Simple program ====
Simple, fast, produces same output as the Math::Roman module and the Raku example, less crazy than writing a Latin program, and doesn't require experimental modules like the Raku translation.
<langsyntaxhighlight lang="perl">my @symbols = ( [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'] );
 
sub roman {
Line 4,972 ⟶ 5,666:
}
 
say roman($_) for 1..2012;</langsyntaxhighlight>
 
==== Using a module ====
<langsyntaxhighlight lang="perl">use Math::Roman qw/roman/;
say roman($_) for 1..2012'</langsyntaxhighlight>
 
==== Ported version of Raku ====
<langsyntaxhighlight lang="perl">use List::MoreUtils qw( natatime );
 
my %symbols = (
Line 5,001 ⟶ 5,695:
};
 
print roman($_) . "\n" for 1..2012;</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<syntaxhighlight lang="phix">
<span style="color: #008080;">function</span> <span style="color: #000000;">toRoman</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
with javascript_semantics
<span style="color: #008080;">constant</span> <span style="color: #000000;">roman</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"M"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"CM"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"D"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"CD"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"C"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"XC"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"L"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"XL"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"X"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"IX"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"V"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"IV"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"I"</span><span style="color: #0000FF;">},</span>
function toRoman(integer v)
<span style="color: #000000;">decml</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">900</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">500</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">400</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">100</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">90</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">50</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">40</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span> <span style="color: #0000FF;">}</span>
sequence roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"},
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
decml = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
<span style="color: #004080;">integer</span> <span style="color: #000000;">val</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">v</span>
string res = ""
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">roman</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer val = v
<span style="color: #008080;">while</span> <span style="color: #000000;">val</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">decml</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">do</span>
for i=1 to length(roman) do
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">roman</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
while val>=decml[i] do
<span style="color: #000000;">val</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">decml</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
res &= roman[i]
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
val -= decml[i]
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end while
<span style="color: #000080;font-style:italic;">-- return res</span>
end for
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- (for output)</span>
return {v,res} -- (for output)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end function
 
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1990</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2008</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1666</span><span style="color: #0000FF;">},</span><span style="color: #000000;">toRoman</span><span style="color: #0000FF;">)</span>
?apply({1990,2008,1666},toRoman)
<!--</lang>-->
</syntaxhighlight>
{{out}}
<pre>
{{1990,"MCMXC"},{2008,"MMVIII"},{1666,"MDCLXVI"}}
</pre>
=== cheating slightly ===
<syntaxhighlight lang="phix">
with javascript_semantics
requires("1.0.5")
function toRoman(integer n)
return {n,sprintf("%R",n)}
end function
</syntaxhighlight>
same output (builtins\VM\pprntfN.e/toRoman() is somewhat more obfuscated and faster than the above)
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def romanEnc /# n -- s #/
Line 5,051 ⟶ 5,755:
enddef
 
1968 romanEnc print</langsyntaxhighlight>
{{trans|Lua}}
<langsyntaxhighlight Phixmontilang="phixmonti">def romanEnc /# n -- s #/
var k
( ( 1000 "M" ) ( 900 "CM" ) ( 500 "D" ) ( 400 "CD" ) ( 100 "C" ) ( 90 "XC" )
Line 5,070 ⟶ 5,774:
enddef
 
1968 romanEnc</langsyntaxhighlight>
Without vars
<langsyntaxhighlight Phixmontilang="phixmonti">def romanEnc /# n -- s #/
>ps
( ( 1000 "M" ) ( 900 "CM" ) ( 500 "D" ) ( 400 "CD" ) ( 100 "C" ) ( 90 "XC" )
Line 5,090 ⟶ 5,794:
enddef
 
1968 romanEnc</langsyntaxhighlight>
 
=={{header|PHP}}==
{{works with|PHP|4+ tested in 5.2.12}}
<langsyntaxhighlight lang="php">
/**
* int2roman
Line 5,155 ⟶ 5,859:
return $numeral . $leastSig;
}
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
List = [455,999,1990,1999,2000,2001,2008,2009,2010,2011,2012,1666,3456,3888,4000],
foreach(Val in List)
printf("%4d: %w\n", Val, roman_encode(Val))
end,
nl.
 
roman_encode(Val) = Res =>
if Val <= 0 then
Res := -1
else
Arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
Roman = ["M", "CM", "D", "CD", "C", "XC","L","XL","X","IX","V","IV","I"],
Res = "",
foreach(I in 1..Arabic.length)
while(Val >= Arabic[I])
Res := Res ++ Roman[I],
Val := Val - Arabic[I]
end
end
end.</syntaxhighlight>
 
{{out}}
<pre> 455: CDLV
999: CMXCIX
1990: MCMXC
1999: MCMXCIX
2000: MM
2001: MMI
2008: MMVIII
2009: MMIX
2010: MMX
2011: MMXI
2012: MMXII
1666: MDCLXVI
3456: MMMCDLVI
3888: MMMDCCCLXXXVIII
4000: MMMM</pre>
 
===Longest numeral===
Which number encodes to the longest Roman numerals in the interval 1..4000:
<syntaxhighlight lang="picat">go2 =>
All = [Len=I=roman_encode(I) : I in 1..4000,E=roman_encode(I), Len=E.len].sort_down,
println(All[1..2]),
nl.</syntaxhighlight>
{{out}}
<pre>[15 = 3888 = MMMDCCCLXXXVIII,14 = 3887 = MMMDCCCLXXXVII]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de roman (N)
(pack
(make
Line 5,167 ⟶ 5,921:
(link C) ) )
'(M CM D CD C XC L XL X IX V IV I)
(1000 900 500 400 100 90 50 40 10 9 5 4 1) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (roman 1009)
Line 5,176 ⟶ 5,930:
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">import String;
int main(){
write(int2roman(2009) + "\n");
write(int2roman(1666) + "\n");
write(int2roman(1337) + "\n");
}</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* From Wiki Fortran */
roman: procedure (n) returns(character (32) varying);
Line 5,204 ⟶ 5,958:
return (r);
end roman;
</syntaxhighlight>
</lang>
Results:
<pre>
Line 5,215 ⟶ 5,969:
 
=={{header|PL/SQL}}==
<syntaxhighlight lang="pl/sql">
<lang PL/SQL>
 
/*****************************************************************
Line 5,241 ⟶ 5,995:
 
END;
</syntaxhighlight>
</lang>
 
=={{header|plainTeX}}==
TeX has its own way to convert a number into roman numeral, but it produces lowercase letters; the following macro (and usage example), produce uppercase roman numeral.
 
<langsyntaxhighlight lang="tex">\def\upperroman#1{\uppercase\expandafter{\romannumeral#1}}
Anno Domini \upperroman{\year}
\bye</langsyntaxhighlight>
 
=={{header|PowerBASIC}}==
{{trans|BASIC}}
 
{{works with|PB/Win|8+}}
 
{{works with|PB/CC|5}}
 
<lang powerbasic>FUNCTION toRoman(value AS INTEGER) AS STRING
DIM arabic(0 TO 12) AS INTEGER
DIM roman(0 TO 12) AS STRING
ARRAY ASSIGN arabic() = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
ARRAY ASSIGN roman() = "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
 
DIM i AS INTEGER
DIM result AS STRING
 
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
result = result & roman(i)
value = value - arabic(i)
LOOP
NEXT i
toRoman = result
END FUNCTION
 
FUNCTION PBMAIN
'Testing
? "2009 = " & toRoman(2009)
? "1666 = " & toRoman(1666)
? "3888 = " & toRoman(3888)
END FUNCTION</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
Filter ToRoman {
$output = ''
Line 5,321 ⟶ 6,043:
$output
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
19,4,0,2479,3001 | ToRoman
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,338 ⟶ 6,060:
{{libheader|clpfd}}
Library clpfd assures that the program works in both managements : Roman towards Arabic and Arabic towards Roman.
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(clpfd)).
 
roman :-
Line 5,440 ⟶ 6,162:
my_print(A, R) :-
format('~w in roman is ~w~n', [A, R]).
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- roman.
Line 5,451 ⟶ 6,173:
</pre>
 
=={{header|PureBasicPython}}==
===Pythonic===
<lang PureBasic>#SymbolCount = 12 ;0 based count
<syntaxhighlight lang="python">import roman
DataSection
print(roman.toRoman(2022))</syntaxhighlight>
denominations:
Data.s "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" ;0-12
denomValues:
Data.i 1000,900,500,400,100,90,50,40,10,9,5,4,1 ;values in decending sequential order
EndDataSection
 
===Minimalistic structuralism===
;-setup
<syntaxhighlight lang="python">def toRoman(n):
Structure romanNumeral
res='' #converts int to str(Roman numeral)
symbol.s
reg=n #using the numerals (M,D,C,L,X,V,I)
value.i
if reg<4000:#no more than three repetitions
EndStructure
while reg>=1000: #thousands up to MMM
res+='M' #MAX is MMMCMXCIX
Global Dim refRomanNum.romanNumeral(#SymbolCount)
reg-=1000
 
if reg>=900: #nine hundreds in 900-999
Restore denominations
res+='CM'
For i = 0 To #SymbolCount
reg-=900
Read.s refRomanNum(i)\symbol
if reg>=500: #five hudreds in 500-899
Next
res+='D'
 
reg-=500
Restore denomValues
if reg>=400: #four hundreds in 400-499
For i = 0 To #SymbolCount
res+='CD'
Read refRomanNum(i)\value
reg-=400
Next
while reg>=100: #hundreds in 100-399
 
res+='C'
Procedure.s decRoman(n)
reg-=100
;converts a decimal number to a roman numeral
if reg>=90: #nine tens in 90-99
Protected roman$, i
res+='XC'
For i = 0 To #SymbolCount reg-=90
if reg>=50: #five Tens in 50-89
Repeat
If n >= refRomanNum(i)\value res+='L'
roman$ + refRomanNum(i)\symbol reg-=50
nif - refRomanNum(i)\valuereg>=40:
res+='XL' #four Tens
Else
Break reg-=40
EndIf while reg>=10:
res+="X" #tens
ForEver
reg-=10
Next
if reg>=9:
res+='IX' #nine Units
reg-=9
if reg>=5:
res+='V' #five Units
reg-=5
if reg>=4:
res+='IV' #four Units
reg-=4
while reg>0: #three or less Units
res+='I'
reg-=1
return res</syntaxhighlight>
 
ProcedureReturn roman$
EndProcedure
 
If OpenConsole()
 
PrintN(decRoman(1999)) ;MCMXCIX
PrintN(decRoman(1666)) ;MDCLXVI
PrintN(decRoman(25)) ;XXV
PrintN(decRoman(954)) ;CMLIV
 
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</lang>
 
=={{header|Python}}==
===Imperative===
# Version for Python 2
<langsyntaxhighlight lang="python">roman = "MDCLXVmdclxvi"; # UPPERCASE for thousands #
adjust_roman = "CCXXmmccxxii";
arabic = (1000000, 500000, 100000, 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1);
Line 5,535 ⟶ 6,249:
2000,2008,2500,3000,4000,4999,5000,6666,10000,50000,100000,500000,1000000);
for val in test:
print '%d - %s'%(val, arabic_to_roman(val))</langsyntaxhighlight>
An alternative which uses the divmod() function<langsyntaxhighlight lang="python">romanDgts= 'ivxlcdmVXLCDM_'
 
def ToRoman(num):
Line 5,551 ⟶ 6,265:
else:
namoR += r*romanDgts[rdix] + (romanDgts[rdix+1] if(v==1) else '')
return namoR[-1::-1]</langsyntaxhighlight>
 
It is more Pythonic to use zip to iterate over two lists together:
<langsyntaxhighlight lang="python">anums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
rnums = "M CM D CD C XC L XL X IX V IV I".split()
 
Line 5,572 ⟶ 6,286:
for val in test:
print '%d - %s'%(val, to_roman(val))
</syntaxhighlight>
</lang>
 
# Version for Python 3
<langsyntaxhighlight lang="python">def arabic_to_roman(dclxvi):
#===========================
'''Convert an integer from the decimal notation to the Roman notation'''
Line 5,596 ⟶ 6,310:
for val in test:
print("%8d %s" %(val, arabic_to_roman(val)))</langsyntaxhighlight>
 
===Declarative===
Less readable, but a 'one liner':
<langsyntaxhighlight lang="python">rnl = [ { '4' : 'MMMM', '3' : 'MMM', '2' : 'MM', '1' : 'M', '0' : '' }, { '9' : 'CM', '8' : 'DCCC', '7' : 'DCC',
'6' : 'DC', '5' : 'D', '4' : 'CD', '3' : 'CCC', '2' : 'CC', '1' : 'C', '0' : '' }, { '9' : 'XC',
'8' : 'LXXX', '7' : 'LXX', '6' : 'LX', '5' : 'L', '4' : 'XL', '3' : 'XXX', '2' : 'XX', '1' : 'X',
Line 5,610 ⟶ 6,324:
# Option 2
def number2romannumeral(n):
return reduce(lambda x, y: x + y, map(lambda x, y: rnl[x][y], range(4), str(n).zfill(4))) if -1 < n < 5000 else None</langsyntaxhighlight>
 
 
Line 5,616 ⟶ 6,330:
{{works with|Python|3}}
{{Trans|Haskell}}
<langsyntaxhighlight lang="python">'''Encoding Roman Numerals'''
 
from functools import reduce
Line 5,629 ⟶ 6,343:
q, r = divmod(a, m)
return (r, s * q)
 
return concat(snd(mapAccumL(go)(n)(
zip([
Line 5,686 ⟶ 6,401:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>MDCLXVI
Line 5,699 ⟶ 6,414:
Pasting epitomised.
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ ""
swap 1000 /mod $ "M" rot of rot swap join swap
dup 900 < not if [ 900 - dip [ $ "CM" join ] ]
Line 5,717 ⟶ 6,432:
1990 dup echo say " = " ->roman echo$ cr
2008 dup echo say " = " ->roman echo$ cr
1666 dup echo say " = " ->roman echo$ cr</langsyntaxhighlight>
 
{{Out}}
Line 5,727 ⟶ 6,442:
=={{header|R}}==
R has a built-in function, <code>[https://svn.r-project.org/R/trunk/src/library/utils/R/roman.R as.roman]</code>, for conversion to Roman numerals. The implementation details are found in <code>utils:::.numeric2roman</code> (see previous link), and <code>utils:::.roman2numeric</code>, for conversion back to Arabic decimals.
<langsyntaxhighlight Rlang="r">as.roman(1666) # MDCLXVI</langsyntaxhighlight>
Since the object <code>as.roman</code> creates is just an integer vector with a class, you can do arithmetic with Roman numerals:
<langsyntaxhighlight Rlang="r">as.roman(1666) + 334 # MM</langsyntaxhighlight>
 
=={{header|Racket}}==
Straight recursion:
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (encode/roman number)
(cond ((>= number 1000) (string-append "M" (encode/roman (- number 1000))))
Line 5,748 ⟶ 6,463:
((>= number 4) (string-append "IV" (encode/roman (- number 4))))
((>= number 1) (string-append "I" (encode/roman (- number 1))))
(else "")))</langsyntaxhighlight>
 
Using for/fold and quotient/remainder to remove repetition:
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (number->list n)
(for/fold ([result null])
Line 5,768 ⟶ 6,483:
1000 1009 1444 1666 1945 1997 1999 2000 2008 2010 2011 2500
3000 3999)])
(printf "~a ~a\n" n (encode/roman n)))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>my %symbols =
1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C",
500 => "D", 1_000 => "M";
Line 5,794 ⟶ 6,509:
for 1 .. 2_010 -> $x {
say roman($x);
}</langsyntaxhighlight>
 
=={{header|Red}}==
Straight iterative solution:
<syntaxhighlight lang="red">
<lang Red>
Red []
table: [1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 5 V 4 IV 1 I]
 
table: [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]
 
to-Roman: function [n [integer!] return: [string!]][
Line 5,808 ⟶ 6,525:
 
foreach number [40 33 1888 2016][print [number ":" to-Roman number]]
</syntaxhighlight>
</lang>
Straight recursive solution:
<syntaxhighlight lang="red">
<lang Red>
Red []
table: [1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 5 V 4 IV 1 I]
 
table: [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]
 
to-Roman: func [n [integer!] return: [string!]][
Line 5,822 ⟶ 6,541:
 
foreach number [40 33 1888 2016][print [number ":" to-Roman number]]
</syntaxhighlight>
</lang>
This solution builds, using metaprogramming, a `case` table, that relies on recursion to convert every digit.
 
<syntaxhighlight lang="red">
<lang Red>
Red []
 
to-Roman: function [n [integer!]] reduce [
'case collect [
Line 5,835 ⟶ 6,556:
 
foreach number [40 33 1888 2016][print [number ":" to-Roman number]]
</syntaxhighlight>
</lang>
 
=={{header|Retro}}==
This is a port of the [[Forth]] code; but returns a string rather than displaying the roman numerals. It only handles numbers between 1 and 3999.
 
<syntaxhighlight lang="retro">
<lang Retro>
: vector ( ...n"- )
here [ &, times ] dip : .data ` swap ` + ` @ ` do ` ; ;
Line 5,865 ⟶ 6,586:
dup 1 3999 within 0 =
[ "EX LIMITO!\n" ] [ "IVXLCDM" swap record here ] if ;
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">roman: procedure
arg number
 
Line 5,885 ⟶ 6,606:
end
end
return result</langsyntaxhighlight>
===version 2===
This version of a REXX program allows almost any non-negative decimal integer.
Line 5,903 ⟶ 6,624:
The general REXX code is bulkier than most at it deals with &nbsp; ''any'' &nbsp; non-negative decimal number, &nbsp; and more
<br>boilerplate code is in the general REXX code to handle the above versions.
<langsyntaxhighlight lang="rexx">/*REXX program converts (Arabic) non─negative decimal integers (≥0) ───► Roman numerals.*/
numeric digits 10000 /*decimal digs can be higher if wanted.*/
parse arg # /*obtain optional integers from the CL.*/
Line 5,955 ⟶ 6,676:
if pos(_, #)\==0 then #=changestr(_, #, copies('M', i))
end /*i*/
return #</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]]. <br><br>
'''output''' &nbsp; when using the default (internal) input):
Line 6,053 ⟶ 6,774:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
roman = ["M", "CM", "D", "CD", "C" ,"XC", "L", "XL" ,"X", "IX", "V", "IV", "I"]
Line 6,070 ⟶ 6,791:
next
return result
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
{{trans|Python}}
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ { 1000 900 500 400 100 90 50 40 10 9 5 4 1 }
{ "M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX"
"V" "IV" "I" } → divs rdig
'''IF''' DUP 5000 < '''THEN'''
"" SWAP 1 13 '''FOR''' j
divs j GET MOD LAST / IP ROT SWAP
'''WHILE''' DUP '''REPEAT'''
rdig j GET ROT SWAP + SWAP 1 - '''END'''
DROP SWAP
'''NEXT'''
'''END''' DROP
≫ ''''→ROM'''' STO
|
'''→ROM''' ''( n -- "ROMAN" )''
store tables
if n < 5000 then
scan divisors
x,y = divmod(n, divisor)
if x > 0 then
add related digit x times
n = y
clean stack
|}
===Alternate version===
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ '''IF''' DUP 5000 < '''THEN'''
{ "IIIVIIIX" "XXXLXXXC" "CCCDCCCM" }
{ 11 21 31 43 44 54 64 74 87 88 } → rom args
≪ "" SWAP
1 3 '''FOR''' j
10 MOD LAST / IP
'''IF''' SWAP '''THEN'''
args LAST GET 10 MOD LAST / IP
rom j GET ROT ROT SUB ROT + SWAP '''END'''
'''NEXT''' ≫
'''WHILE''' DUP '''REPEAT''' 1 - "M" ROT + SWAP '''END'''
DROP '''END'''
≫ ''''→ROM'''' STO
|
'''→ROM''' ''( n -- "M..CXVI" ) ''
collapsed Roman digits
10 arguments to extract Roman digits
initialize stack
process units to hundreds
divmod(n,10)
if last digit ≠ 0 then
get extraction arguments
extract Roman digit
add thousands if any
clean stack
|}
 
=={{header|Ruby}}==
Roman numeral generation was used as an example for demonstrating [http://www.xpsd.org/cgi-bin/wiki?TestDrivenDevelopmentTutorialRomanNumerals Test Driven Development] in Ruby. The solution came to be:
<langsyntaxhighlight lang="ruby">Symbols = { 1=>'I', 5=>'V', 10=>'X', 50=>'L', 100=>'C', 500=>'D', 1000=>'M' }
Subtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ]
 
Line 6,087 ⟶ 6,877:
[1990, 2008, 1666].each do |i|
puts "%4d => %s" % [i, roman(i)]
end</langsyntaxhighlight>
 
{{out}}
Line 6,098 ⟶ 6,888:
Another shorter version if we don't consider calculating the substractors:
 
<langsyntaxhighlight lang="ruby">
Symbols = [ [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'] ]
 
Line 6,105 ⟶ 6,895:
Symbols.each { |arabic_rep, roman_rep| return roman_rep + arabic_to_roman(arabic - arabic_rep) if arabic >= arabic_rep }
end
</syntaxhighlight>
</lang>
 
Yet another way to solve it in terms of reduce
 
<langsyntaxhighlight lang="ruby">
Symbols = [ [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'] ]
 
Line 6,118 ⟶ 6,908:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<lang runbasic>[loop]
input "Input value:";val$
print roman$(val$)
goto [loop]
 
' ------------------------------
' Roman numerals
' ------------------------------
FUNCTION roman$(val$)
a2r$ = "M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1"
v = val(val$)
for i = 1 to 13
r$ = word$(a2r$,i,",")
a = val(word$(r$,2,":"))
while v >= a
roman$ = roman$ + word$(r$,1,":")
v = v - a
wend
next i
END FUNCTION</lang>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">struct RomanNumeral {
symbol: &'static str,
value: u32
Line 6,181 ⟶ 6,949:
println!("{:2$} = {}", n, to_roman(n), 4);
}
}</langsyntaxhighlight>{{out}}
<pre>
2014 = MMXIV
Line 6,192 ⟶ 6,960:
=={{header|Scala}}==
{{works with|Scala|2.8}}
<langsyntaxhighlight lang="scala">val romanDigits = Map(
1 -> "I", 5 -> "V",
10 -> "X", 50 -> "L",
Line 6,204 ⟶ 6,972:
case Some(key) => romanDigits(key) + toRoman(n - key)
case None => ""
}</langsyntaxhighlight>
{{Out}}
<pre>scala> List(1990, 2008, 1666) map toRoman
res55: List[String] = List(MCMXC, MMVIII, MDCLXVI)</pre>
===Using foldLeft===
<langsyntaxhighlight Scalalang="scala">def toRoman( v:Int ) : String = {
val romanNumerals = List(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")
Line 6,222 ⟶ 6,990:
test(1990)
test(2008)
test(1666)</langsyntaxhighlight>
===Different code-style===
<langsyntaxhighlight Scalalang="scala">def toRoman(num: Int): String = {
case class RomanUnit(value: Int, token: String)
val romanNumerals = List(
Line 6,249 ⟶ 7,017:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>1990 => MCMXC
Line 6,258 ⟶ 7,026:
This uses format directives supported in Chez Scheme since v6.9b; YMMV.
 
<langsyntaxhighlight lang="scheme">(define (to-roman n)
(format "~@r" n))</langsyntaxhighlight>
 
This is a general example using Chicken Scheme.
<langsyntaxhighlight lang="scheme">(define roman-decimal
'(("M" . 1000)
("CM" . 900)
Line 6,296 ⟶ 7,064:
(printf "~a ~a\n" (car n) (to-roman (car n)))
(loop (cdr n))))
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
Line 6,304 ⟶ 7,072:
which writes a roman numeral to a string.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "stdio.s7i";
include "wrinum.s7i";
Line 6,315 ⟶ 7,083:
writeln(str(ROMAN, number));
end for;
end func;</langsyntaxhighlight>
 
Original source [http://seed7.sourceforge.net/algorith/puzzles.htm#roman_numerals].
Line 6,321 ⟶ 7,089:
=={{header|SenseTalk}}==
 
<langsyntaxhighlight lang="sensetalk">function RomanNumeralsEncode number
put [
(1, "I"),
Line 6,347 ⟶ 7,115:
end repeat
return numerals
end RomanNumeralsEncode</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sensetalk">repeat for each item in [
1990,
2008,
Line 6,355 ⟶ 7,123:
]
put RomanNumeralsEncode(it)
end repeat</langsyntaxhighlight>
 
{{out}}
Line 6,365 ⟶ 7,133:
 
=={{header|SETL}}==
<langsyntaxhighlight lang="ada">examples := [2008, 1666, 1990];
 
for example in examples loop
Line 6,381 ⟶ 7,149:
end loop;
return roman;
end;</langsyntaxhighlight>
{{out}}
<pre>MMVIII
Line 6,388 ⟶ 7,156:
 
=={{header|Shen}}==
<langsyntaxhighlight lang="shen">
(define encodeGlyphs
ACC 0 _ -> ACC
Line 6,398 ⟶ 7,166:
N -> (encodeGlyphs "" N ["M" 1000 "CM" 900 "D" 500 "CD" 400 "C" 100 "XC" 90 "L" 50 "XL" 40 "X" 10 "IX" 9 "V" 5 "IV" 4 "I" 1])
)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,413 ⟶ 7,181:
=={{header|Sidef}}==
{{trans|ActionScript}}
<langsyntaxhighlight lang="ruby">func arabic2roman(num, roman='') {
static lookup = [
:M:1000, :CM:900, :D:500,
Line 6,431 ⟶ 7,199:
say("1990 in roman is " + arabic2roman(1990));
say("2008 in roman is " + arabic2roman(2008));
say("1666 in roman is " + arabic2roman(1666));</langsyntaxhighlight>
{{out}}
<pre>1990 in roman is MCMXC
Line 6,438 ⟶ 7,206:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
 
TEXT PROCEDURE TOROMAN(N); INTEGER N;
Line 6,478 ⟶ 7,246:
 
END PROGRAM;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,490 ⟶ 7,258:
{{works with|Smalltalk/X}}
in ST/X, integers already know how to print themselves as roman number:
<syntaxhighlight lang ="smalltalk">2013 printRomanOn:Stdout naive:false</langsyntaxhighlight>
{{out}}
<pre>
MMXIII</pre>
the implementation is:
<langsyntaxhighlight lang="smalltalk">
printRomanOn:aStream naive:naive
"print the receiver as roman number to the argument, aStream.
Line 6,549 ⟶ 7,317:
] doWhile:[ repeatFlag and:[ restValue >= rValue] ].
].
</syntaxhighlight>
</lang>
 
=={{header|SNOBOL4}}==
Adapted from [http://burks.bton.ac.uk/burks/language/snobol/catspaw/tutorial/ch6.htm Catspaw SNOBOL Tutorial, Chapter 6]
 
<langsyntaxhighlight lang="snobol4">
* ROMAN(N) - Convert integer N to Roman numeral form.
*
Line 6,585 ⟶ 7,353:
OUTPUT = " 944 = " ROMAN(944)
 
END</langsyntaxhighlight>
{{out}}
<pre>
Line 6,595 ⟶ 7,363:
Here's a non-recursive version, and a Roman-to-Arabic converter to boot.
 
<langsyntaxhighlight SNOBOL4lang="snobol4">* # Arabic to Roman
define('roman(n)s,ch,val,str') :(roman_end)
roman roman = ge(n,4000) n :s(return)
Line 6,623 ⟶ 7,391:
astr = astr r '=' arabic(r) ' ' :(tloop)
out output = rstr; output = astr
end</langsyntaxhighlight>
 
{{out}}
Line 6,630 ⟶ 7,398:
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">a2r(a)=
r = ""
n = [["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"],[1000,900,500,400,100,90,50,40,10,9,5,4,1]]
Line 6,645 ⟶ 7,413:
> i, 1..#.size(t,1)
#.output(t[i]," = ",a2r(t[i]))
<</langsyntaxhighlight>
{{out}}
<pre>
Line 6,654 ⟶ 7,422:
 
=={{header|SQL}}==
<syntaxhighlight lang="sql">
<lang SQL>
--
-- This only works under Oracle and has the limitation of 1 to 3999
Line 6,664 ⟶ 7,432:
--------------- ---------------
MDCLXVI mdclxvi
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func ator(var n: Int) -> String {
 
var result = ""
Line 6,692 ⟶ 7,460:
}
return result
}</langsyntaxhighlight>
Sample call:
{{works with|Swift|1.x}}
<langsyntaxhighlight lang="swift">println(ator(1666)) // MDCLXVI</langsyntaxhighlight>
{{works with|Swift|2.0}}
<langsyntaxhighlight lang="swift">print(ator(1666)) // MDCLXVI</langsyntaxhighlight>
{{output}}
<pre>MDCLXVI </pre>
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
def digits: [(M:1000"1"), (CM:900"1"), (D:500"1"), (CD:400"1"), (C:100"1"), (XC:90"1"), (L:50"1"), (XL:40"1"), (X:10"1"), (IX:9"1"), (V:5"1"), (IV:4"1"), (I:1"1")];
templates encodeRoman
@: 1;
'$ -> ($)"1" -> #;' !
when <$digits($@)::value..> do
$digits($@)::key !
$ - $digits($@)::value -> #
when <1"1"..> do
@:$@ + 1;
$ -> #
Line 6,722 ⟶ 7,490:
' -> !OUT::write
1666 -> encodeRoman -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,731 ⟶ 7,499:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc to_roman {i} {
set map {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}
foreach {value roman} $map {
Line 6,740 ⟶ 7,508:
}
return $res
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
<lang ti83b>PROGRAM:DEC2ROM
:"="→Str1
:Lbl ST
:ClrHome
:Disp "NUMBER TO"
:Disp "CONVERT:"
:Input A
:If fPart(A) or A≠abs(A)
:Then
:Goto PI
:End
:A→B
:While B≥1000
:Str1+"M"→Str1
:B-1000→B
:End
:If B≥900
:Then
:Str1+"CM"→Str1
:B-900→B
:End
:If B≥500
:Then
:Str1+"D"→Str1
:B-500→B
:End
:If B≥400
:Then
:Str1+"CD"?Str1
:B-400→B
:End
:While B≥100
:Str1+"C"→Str1
:B-100→B
:End
:If B≥90
:Then
:Str1+"XC"→Str1
:B-90→B
:End
:If B≥50
:Then
:Str1+"L"→Str1
:B-50→B
:End
:If B≥40
:Then
:Str1+"XL"→Str1
:B-40→B
:End
:While B≥10
:Str1+"X"→Str1
:B-10→B
:End
:If B≥9
:Then
:Str1+"IX"→Str1
:B-9→B
:End
:If B≥5
:Then
:Str1+"V"→Str1
:B-5→B
:End
:If B≥4
:Then
:Str1+"IV"→Str1
:B-4→B
:End
:While B>0
:Str1+"I"→Str1
:B-1→B
:End
:ClrHome
:Disp A
:Disp Str1
:Stop
:Lbl PI
:ClrHome
:Disp "THE NUMBER MUST"
:Disp "BE A POSITIVE"
:Disp "INTEGER."
:Pause
:Goto ST
</lang>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
LOOP arab_number="1990'2008'1666"
Line 6,836 ⟶ 7,517:
PRINT "Arabic number ",arab_number, " equals ", roman_number
ENDLOOP
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,844 ⟶ 7,525:
</pre>
 
== {{header|uBasic/4tHTypeScript}} ==
{{trans|BBC BasicDWScript}}
Weights and symbols in tuples.
<lang>Push 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000
<syntaxhighlight lang="javascript">
' Initialize array
// Roman numerals/Encode
For i = 12 To 0 Step -1
@(i) = Pop()
Next
' Calculate and print numbers
Print 1999, : Proc _FNroman (1999)
Print 2014, : Proc _FNroman (2014)
Print 1666, : Proc _FNroman (1666)
Print 3888, : Proc _FNroman (3888)
 
const weightsSymbols: [number, string][] =
End
[[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']];
// 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded
// with these symbols.
 
function toRoman(n: number): string {
_FNroman Param (1) ' ( n --)
var roman = ""; // Result
Local (1) ' Define b@
for (i = 0; i <= 12 && n > 0; i++) {
' Try all numbers in array
var w = weightsSymbols[i][0];
For b@ = 12 To 0 Step -1
while (n >= w) {
Do While a@ > @(b@) - 1 ' Several occurences of same number?
roman += weightsSymbols[i][1];
GoSub ((b@ + 1) * 10) ' Print roman digit
n -= w;
a@ = a@ - @(b@) ' Decrement number
Loop}
Next}
return roman;
}
 
console.log(toRoman(1990)); // MCMXC
Print ' Terminate line
console.log(toRoman(2022)); // MMXXII
Return
console.log(toRoman(3888)); // MMMDCCCLXXXVIII
' Print roman digits
</syntaxhighlight>
10 Print "I"; : Return
{{out}}
20 Print "IV"; : Return
<pre>
30 Print "V"; : Return
MCMXC
40 Print "IX"; : Return
MMXXII
50 Print "X"; : Return
MMMDCCCLXXXVIII
60 Print "XL"; : Return
</pre>
70 Print "L"; : Return
80 Print "XC"; : Return
90 Print "C"; : Return
100 Print "CD"; : Return
110 Print "D"; : Return
120 Print "CM"; : Return
130 Print "M"; : Return</lang>
 
=={{header|UNIX Shell}}==
{{trans|Tcl}}
{{works with|bash}}
<langsyntaxhighlight lang="bash">roman() {
local values=( 1000 900 500 400 100 90 50 40 10 9 5 4 1 )
local roman=(
Line 6,910 ⟶ 7,584:
for test in 1999 24 944 1666 2008; do
printf "%d = %s\n" $test $(roman $test)
done</langsyntaxhighlight>
{{out}}
<pre>
Line 6,928 ⟶ 7,602:
CCCC are replaced by CD. The substitution operator (%=) is helpful
here.
<langsyntaxhighlight Ursalalang="ursala">#import nat
 
roman =
Line 6,934 ⟶ 7,608:
-+
'IIII'%='IV'+ 'VIIII'%='IX'+ 'XXXX'%='XL'+ 'LXXXX'%='XC'+ 'CCCC'%='CD'+ 'DCCCC'%='CM',
~&plrDlSPSL/'MDCLXVI'+ iota*+ +^|(^|C/~&,\/division)@rlX=>~&iNC <1000,500,100,50,10,5>+-</langsyntaxhighlight>
This test program applies the function to each member of a list of numbers.
<langsyntaxhighlight Ursalalang="ursala">#show+
 
test = roman* <1990,2008,1,2,64,124,1666,10001></langsyntaxhighlight>
{{out}}
<pre>MCMXC
Line 6,951 ⟶ 7,625:
=={{header|Vala}}==
{{trans|D}}
<langsyntaxhighlight lang="vala">string to_roman(int n)
requires (n > 0 && n < 5000)
{
Line 6,976 ⟶ 7,650:
print("%s\n", to_roman(3456));
print("%s\n", to_roman(2488));
}</langsyntaxhighlight>
 
{{out}}
Line 6,986 ⟶ 7,660:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function roman(n As Integer) As String
roman = WorksheetFunction.roman(n)
End Function
Line 6,994 ⟶ 7,668:
Debug.Print roman(CInt(x)); " ";
Next x
End Sub</langsyntaxhighlight>{{out}}
<pre>X MMXVI DCCC MMDCCLXIX MDCLXVI CDLXXVI MCDLIII </pre>
 
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang="vedit">// Main program for testing the function
//
do {
Line 7,029 ⟶ 7,703:
}
Buf_Quit(OK)
Return</langsyntaxhighlight>
 
{{out}}
Line 7,038 ⟶ 7,712:
2011 = MMXI</pre>
 
=={{header|VisualV Basic(Vlang)}}==
<syntaxhighlight lang="Zig">
{{trans|BASIC}}
const numerals = {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"}
 
fn main() {
<lang vb>Function toRoman(value) As String
println(encode(1990))
Dim arabic As Variant
println(encode(2008))
Dim roman As Variant
println(encode(1666))
}
 
fn encode(number int) string {
arabic = Array(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
mut num := number
roman = Array("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
mut result := ""
if number < 1 || number > 5000 {return result}
for digit, roman in numerals {
for num >= digit {
num -= digit
result += roman
}
}
return result
}
</syntaxhighlight>
 
{{out}}
Dim i As Integer, result As String
<pre>
 
MCMXC
For i = 0 To 12
MMVIII
Do While value >= arabic(i)
MDCLXVI
result = result + roman(i)
</pre>
value = value - arabic(i)
Loop
Next i
 
toRoman = result
End Function
 
Sub Main()
MsgBox toRoman(Val(InputBox("Number, please")))
End Sub</lang>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">var romans = [
[1000, "M"],
[900, "CM"],
Line 7,097 ⟶ 7,777:
System.print(encode.call(1666))
System.print(encode.call(2008))
System.print(encode.call(2020))</langsyntaxhighlight>
 
{{out}}
Line 7,105 ⟶ 7,785:
MMVIII
MMXX
</pre>
 
=={{header|XBasic}}==
{{trans|DWScript}}
{{works with|Windows XBasic}}
<lang xbasic>
PROGRAM "romanenc"
VERSION "0.0000"
 
DECLARE FUNCTION Entry()
INTERNAL FUNCTION ToRoman$(aValue%%)
 
' 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded with these symbols.
 
FUNCTION Entry()
PRINT ToRoman$(1990) ' MCMXC
PRINT ToRoman$(2018) ' MMXVIII
PRINT ToRoman$(3888) ' MMMDCCCLXXXVIII
END FUNCTION
 
FUNCTION ToRoman$(aValue%%)
DIM weights%%[12]
DIM symbols$[12]
 
weights%%[0] = 1000
weights%%[1] = 900
weights%%[2] = 500
weights%%[3] = 400
weights%%[4] = 100
weights%%[5] = 90
weights%%[6] = 50
weights%%[7] = 40
weights%%[8] = 10
weights%%[9] = 9
weights%%[10] = 5
weights%%[11] = 4
weights%%[12] = 1
 
symbols$[0] = "M"
symbols$[1] = "CM"
symbols$[2] = "D"
symbols$[3] = "CD"
symbols$[4] = "C"
symbols$[5] = "XC"
symbols$[6] = "L"
symbols$[7] = "XL"
symbols$[8] = "X"
symbols$[9] = "IX"
symbols$[10] = "V"
symbols$[11] = "IV"
symbols$[12] = "I"
 
destination$ = ""
i@@ = 0
DO WHILE (i@@ <= 12) AND (aValue%% > 0)
DO WHILE aValue%% >= weights%%[i@@]
destination$ = destination$ + symbols$[i@@]
aValue%% = aValue%% - weights%%[i@@]
LOOP
i@@ = i@@ + 1
LOOP
RETURN destination$
END FUNCTION
END PROGRAM
</lang>
{{out}}
<pre>
MCMXC
MMXVIII
MMMDCCCLXXXVIII
</pre>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(defun roman (n)
(define roman-numerals '((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")))
(defun romanize (arabic-numeral numerals roman-numeral)
Line 7,189 ⟶ 7,799:
 
; test the function:
(display (mapcar roman '(10 2016 800 2769 1666 476 1453)))</langsyntaxhighlight>
{{out}}
<pre>(x mmxvi dccc mmdcclxix mdclxvi cdlxxvi mcdliii)</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">proc Rom(N, A, B, C); \Display 1..9 in Roman numerals
int N, A, B, C, I;
[case N of
Line 7,218 ⟶ 7,828:
for I:= 0 to 7 do
[IntOut(0, Tbl(I)); Text(0, ". "); Roman(Tbl(I)); CrLf(0)];
]</langsyntaxhighlight>
 
{{out}}
Line 7,233 ⟶ 7,843:
 
=={{header|XSLT}}==
<langsyntaxhighlight lang="xslt">
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/data/number">
Line 7,284 ⟶ 7,894:
</xsl:template>
</xsl:stylesheet>
</syntaxhighlight>
</lang>
 
=={{header|Yabasic}}==
<lang Yabasic>roman$ = "M, CM, D, CD, C, XC, L, XL, X, IX, V, IV, I"
decml$ = "1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1"
sub toRoman$(value)
local res$, i, roman$(1), decml$(1), long
long = token(roman$, roman$(), ", ")
long = token(decml$, decml$(), ", ")
for i=1 to long
while(value >= val(decml$(i)))
res$ = res$ + roman$(i)
value = value - val(decml$(i))
wend
next i
return res$
end sub
print 400, " ", toRoman$(400)
print 1990, " ", toRoman$(1990)
print 2008, " ", toRoman$(2008)
print 2009, " ", toRoman$(2009)
print 1666, " ", toRoman$(1666)
print 3888, " ", toRoman$(3888)
//Output:
// 400 = CD
// 1990 = MCMXC
// 2008 = MMVIII
// 2009 = MMIX
// 1666 = MDCLXVI
// 3888 = MMMDCCCLXXXVIII</lang>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var [const] romans = L(
L("M", 1000), L("CM", 900), L("D", 500), L("CD", 400), L("C", 100),
L("XC", 90), L("L", 50), L("XL", 40), L("X", 10), L("IX", 9),
Line 7,328 ⟶ 7,905:
foreach R,N in (romans){ text += R*(i/N); i = i%N; }
return(text);
}</langsyntaxhighlight>
<pre>
toRoman(1990) //-->"MCMXC"
Line 7,336 ⟶ 7,913:
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: decimal_roman
input: 12
output: 'XII'
</syntaxhighlight>
</lang>
 
=={{header|Zoea Visual}}==
Line 7,347 ⟶ 7,924:
=={{header|Zsh}}==
Based on the python solution.
<langsyntaxhighlight lang="zsh">function printroman () {
local -a conv
local number=$1 div rom num out
Line 7,358 ⟶ 7,935:
done
echo $out
}</langsyntaxhighlight>
7,794

edits