Ashley Sheridan​.co.uk

Roman to Decimal Conversion

Posted on

Tags:

Clock face showing Roman numeralsI stumbled across a recent post on Stack Overflow where someone was asking how to convert from Roman numerals to decimal with PHP. The answers already there seemed more complicated than the ought to be, so I figured I'd write a quick function for it myself.

This is only a very basic attempt, and doesn't take into account certain rules, like Roman digits which shouldn't be repeated, and what values can appear in what order. Having said that, for a valid Roman numeric string, this should calculate the correct value:

$roman = strtolower($_GET['roman']); $values = array( 'i' => 1, 'v' => 5, 'x' => 10, 'l' => 50, 'c' => 100, 'd' => 500, 'm' => 1000, ); $total = 0; for($i=0; $i<strlen($roman); $i++) { $v = $values[substr($roman, $i, 1)]; $v2 = ($i < strlen($roman))?$values[substr($roman, $i+1, 1)]:0; if($v2 && $v < $v2) { $total += ($v2 - $v); $i++; } else $total += $v; } echo $total;

Basically, this loops through a Roman-formatted string character by character, and converts each one to a value. It compares each value to the next one in the string if there is one, and if it's less, it subtracts it from the next value and adds the result to the total, otherwise it just adds the value to the total. To compensate for the fact that two digits get 'used up' when a subtraction is taking place, an extra incrememnt is added at line 21, making sure the pointer $i in the loop is looking at the right character in the string.

And for those interested, here is my solution to converting Roman numerals to decimal in PHP on SA.

Comments

Leave a comment