Pick a Theme:
       
       

Converting From Roman Numerals To Decimal
Web Script

October 13, 2011

Menu
Home

Outdoors (12)
Submit Comments (1)
Outdoors (3)
Food (19)
Erudition (12)
Projects (6)
Scouting (4)
Programming (5)
Art (4)
Bad math (9)
Mis-information (4)
Minecraft (4)
Random (12)

Ok, part 2, converting back to a real number for roman numerals (part 1 is here)...First of all, here are the functions to play with:

Decimal Number:
Roman Number:

Roman Number:
Decimal Number:

Reverse Engineering

I very quickly realized that the likes of 4 (IV) and 9 (IX) were once again going to bugger us up. So we will hunt those down first in the array (after we get rid of all the stupidly huge numbers).

<?php
function from_roman_num($temp) { 
  
$values = array("M6+" => 1000000000"M5+" => 100000000"M4+" => 10000000,
                  
"M3+" => 1000000"M2+" => 100000"M1+" => 10000,
                  
"CM" => 900"M" => 1000"CD" => 400"D" => 500,
                  
"XC" => 90"C" => 100"XL" => 40"L" => 50"IX" => 9,
                  
"X" => 10"IV" => 4"V" => 5"I" => 1);
?>

Alright, we need to parse the string of letters based on the above array. We also need to figure out how long the number is. We also need to be able to check both 1 digit and 2 digit numbers. We also need to make sure everything is in capitals. I also hate it when people use single letters for variables, it doesn't cost you anything to use 3 or 5 letters and have other people be able to follow...

I'm using a bunch of sub string and string length hunts here. When a number is found, we will onto the total and then remove it from the number. Turns out my first guess was close, but not very. So here is the one that does work:

<?php
function from_roman_num($temp) { 
  
$values = array("M6+" => 1000000000"M5+" => 100000000"M4+" => 10000000,
                  
"M3+" => 1000000"M2+" => 100000"M1+" => 10000,
                  
"CM" => 900"M" => 1000"CD" => 400"D" => 500,
                  
"XC" => 90"C" => 100"XL" => 40"L" => 50"IX" => 9,
                  
"X" => 10"IV" => 4"V" => 5"I" => 1);
  
strtoupper($temp); 
  
$temp_len strlen($temp); 
  for (
$i=0$i <= $temp_len95++) { 
    foreach (
$values as $output => $number) { 
      
$out_len strlen($output); 
      if (
substr($temp$i$out_len) == $output) { 
        
$rebuild += $number
        
$temp substr($temp0$i) . str_repeat(" "$out_len) . substr($temp$i $out_len); 
        
$i += $out_len 1
      } 
    } 
  } 
  return 
$rebuild
}
?>