. */ declare(strict_types=1); namespace Fisharebest\Webtrees\Services; /** * Convert to and from Roman Numerals */ class RomanNumeralsService { // Convert numbers to/from roman numerals const ROMAN_NUMERALS = [ 1000 => 'M', 900 => 'CM', 500 => 'D', 400 => 'CD', 100 => 'C', 90 => 'XC', 50 => 'L', 40 => 'XL', 10 => 'X', 9 => 'IX', 5 => 'V', 4 => 'IV', 1 => 'I', ]; /** * Convert a decimal number to roman numerals * * @param int $number * * @return string */ public function numberToRomanNumerals(int $number): string { if ($number < 1) { // Cannot convert zero/negative numbers return (string) $number; } $roman = ''; foreach (self::ROMAN_NUMERALS as $key => $value) { while ($number >= $key) { $roman .= $value; $number -= $key; } } return $roman; } /** * Convert a roman numeral to decimal * * @param string $roman * * @return int */ public function romanNumeralsToNumber(string $roman): int { $num = 0; foreach (self::ROMAN_NUMERALS as $key => $value) { while (strpos($roman, $value) === 0) { $num += $key; $roman = substr($roman, strlen($value)); } } return $num; } }