Snippet Name: Roman2dec and Dec2Roman
Description: A function that converts to and from Roman numerals.
Also see: » BR2NL Function: Opposite of NL2BR
» Convert Seconds to Hours:Minutes:Secon...
» Convert UK Dates To mySQL Format Dates
» Convert miles to feet, feet to miles, ...
» Convert Minutes to Hours
» Binary to Text and Text to Binary
» Decimal to octal conversion
» Convert minutes to hours #2
» Convert minutes to hours one
» Convert HTML to plain text
» Convert BBCode Tags
Comment: (none)
Language: PHP
Highlight Mode: PHP
Last Modified: March 16th, 2009
|
<?PHP
FUNCTION dec2roman($f)
{
// Return false if either $f is not a real number, $f is bigger than 3999 or $f is lower or equal to 0:
IF(!IS_NUMERIC($f) || $f > 3999 || $f <= 0) RETURN FALSE;
// Define the roman figures:
$roman = ARRAY('M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1);
// Calculate the needed roman figures:
FOREACH($roman AS $k => $v) IF(($amount[$k] = FLOOR($f / $v)) > 0) $f -= $amount[$k] * $v;
// Build the string:
$return = '';
FOREACH($amount AS $k => $v)
{
$return .= $v <= 3 ? STR_REPEAT($k, $v) : $k . $old_k;
$old_k = $k;
}
// Replace some spacial cases and return the string:
RETURN STR_REPLACE(ARRAY('VIV','LXL','DCD'), ARRAY('IX','XC','CM'), $return);
}
// Function to get the decimal value of a roman string:
FUNCTION roman2dec($str = '')
{
// Return false if not at least one letter is in the string:
IF(IS_NUMERIC($str)) RETURN FALSE;
// Define the roman figures:
$roman = ARRAY('M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1);
// Convert the string to an array of roman values:
FOR($i = 0; $i < STRLEN($str); $i++) IF(ISSET($roman[STRTOUPPER($str[$i])])) $values[] = $roman[STRTOUPPER($str[$i])];
// Calculate the sum of that array:
$sum = 0;
WHILE($current = CURRENT($values))
{
$next = NEXT($values);
$next > $current ? $sum += $next - $current + 0 * NEXT($values) : $sum += $current;
}
// Return the value:
RETURN $sum;
}
?>
|