Created
July 19, 2012 08:29
-
-
Save floq-design/3141572 to your computer and use it in GitHub Desktop.
Convert decimal to roman numerals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*integer to roman numeral converter*/ | |
function numberToRoman($num) { | |
// Make sure that we only use the integer portion of the value | |
$n = intval($num); | |
$result = ''; | |
// Declare a lookup array that we will use to traverse the number: | |
$lookup = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, | |
'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40, | |
'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1); | |
foreach ($lookup as $roman => $value) { | |
// Determine the number of matches | |
$matches = intval($n / $value); | |
// Store that many characters | |
$result .= str_repeat($roman, $matches); | |
// Substract that from the number | |
$n = $n % $value; | |
} | |
// The Roman numeral should be built, return it | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment