Tech Tip: Methods for Roman Numeral Conversions
PRODUCT: 4D | VERSION: 14.3 | PLATFORM: Mac & Win
Published On: April 20, 2015
Below are two methods:
NumToRom takes a number and outputs the Roman Numeral representation in text:
// Method: NumToRom C_LONGINT($1;$num_l;$i) C_TEXT($0;$result_t) ARRAY TEXT($roman_t;0) ARRAY LONGINT($decimal_l;0) If (Count parameters=1) $num_l:=$1 APPEND TO ARRAY($roman_t;"I") APPEND TO ARRAY($roman_t;"IV") APPEND TO ARRAY($roman_t;"V") APPEND TO ARRAY($roman_t;"IX") APPEND TO ARRAY($roman_t;"X") APPEND TO ARRAY($roman_t;"XL") APPEND TO ARRAY($roman_t;"L") APPEND TO ARRAY($roman_t;"XC") APPEND TO ARRAY($roman_t;"C") APPEND TO ARRAY($roman_t;"CD") APPEND TO ARRAY($roman_t;"D") APPEND TO ARRAY($roman_t;"CM") APPEND TO ARRAY($roman_t;"M") APPEND TO ARRAY($decimal_l;1) APPEND TO ARRAY($decimal_l;4) APPEND TO ARRAY($decimal_l;5) APPEND TO ARRAY($decimal_l;9) APPEND TO ARRAY($decimal_l;10) APPEND TO ARRAY($decimal_l;40) APPEND TO ARRAY($decimal_l;50) APPEND TO ARRAY($decimal_l;90) APPEND TO ARRAY($decimal_l;100) APPEND TO ARRAY($decimal_l;400) APPEND TO ARRAY($decimal_l;500) APPEND TO ARRAY($decimal_l;900) APPEND TO ARRAY($decimal_l;1000) For ($i;13;1;-1) While ($num_l>=$decimal_l{$i}) $result_t:=$result_t+$roman_t{$i} $num_l:=$num_l-$decimal_l{$i} End while End for $0:=$result_t End if |
RomToNum does the opposite, taking a Roman Numeral representation of a number and outputing the actually numeric value:
// Method: NumToRom C_TEXT($1;$num_t) C_LONGINT($0;$result_l) C_LONGINT($pos_l;$start_l;$length_l;$i) ARRAY TEXT($roman_t;0) ARRAY LONGINT($decimal_l;0) If (Count parameters=1) $num_t:=Uppercase($1) APPEND TO ARRAY($roman_t;"I") APPEND TO ARRAY($roman_t;"IV") APPEND TO ARRAY($roman_t;"V") APPEND TO ARRAY($roman_t;"IX") APPEND TO ARRAY($roman_t;"X") APPEND TO ARRAY($roman_t;"XL") APPEND TO ARRAY($roman_t;"L") APPEND TO ARRAY($roman_t;"XC") APPEND TO ARRAY($roman_t;"C") APPEND TO ARRAY($roman_t;"CD") APPEND TO ARRAY($roman_t;"D") APPEND TO ARRAY($roman_t;"CM") APPEND TO ARRAY($roman_t;"M") APPEND TO ARRAY($decimal_l;1) APPEND TO ARRAY($decimal_l;4) APPEND TO ARRAY($decimal_l;5) APPEND TO ARRAY($decimal_l;9) APPEND TO ARRAY($decimal_l;10) APPEND TO ARRAY($decimal_l;40) APPEND TO ARRAY($decimal_l;50) APPEND TO ARRAY($decimal_l;90) APPEND TO ARRAY($decimal_l;100) APPEND TO ARRAY($decimal_l;400) APPEND TO ARRAY($decimal_l;500) APPEND TO ARRAY($decimal_l;900) APPEND TO ARRAY($decimal_l;1000) $pos_l:=1 For ($i;13;1;-1) If (Match regex("("+$roman_t{$i}+")*";$num_t;$pos_l;$start_l;$length_l)) If ($pos_l=$start_l) $pos_l:=$pos_l+$length_l $length_l:=$length_l/Length($roman_t{$i}) $result_l:=($decimal_l{$i}*$length_l)+$result_l End if End if End for $0:=$result_l End if |
Below is an example of using the methods:
C_LONGINT($num;$res1) C_TEXT($rom;$res2) $num:=1667 $rom:="XVII" $res2:=NumToRom ($num) $res1:=RomToNum ($rom) |
$res1 is 17 and $res2 is "MDCLXVII"