Roman To Numbers

This algorithm converts roman numerals to decimal numbers.



									function RomanToNumber($romanChar) {
	switch ($romanChar)
	{
	case 'I':
		return 1;
	case 'V':
		return 5;
	case 'X':
		return 10;
	case 'L':
		return 50;
	case 'C':
		return 100;
	case 'D':
		return 500;
	case 'M':
		return 1000;
	default:
		break;
	}

	return 0;
}

function RomanToNumbers($roman)
{
	$roman = trim(strtoupper($roman));
	if ($roman == "N") return 0;

	$ptr = 0;
	$values = array();
	$maxDigit = 1000;
	$romanLen = strlen($roman);
	
	while ($ptr < $romanLen)
	{
		$numeral = $roman[$ptr];
		$digit = RomanToNumber($numeral);

		$nextDigit = 0;
		if ($ptr < $romanLen - 1)
		{
			$nextNumeral = $roman[$ptr + 1];
			$nextDigit = RomanToNumber($nextNumeral);

			if ($nextDigit > $digit)
			{
				$maxDigit = $digit - 1;
				$digit = $nextDigit - $digit;
				$ptr++;
			}
		}

		array_push($values, $digit);
		$ptr++;
	}

	$total = 0;
	foreach ($values as $digit)
		$total += $digit;

	return $total;
}
								


Example

									$data = "CDXIX";
$value = RomanToNumbers($data);
								


Output

									419