Skip to content

Instantly share code, notes, and snippets.

@fintara
Last active August 29, 2015 13:55

Revisions

  1. fintara revised this gist Jan 30, 2014. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions DecimalToRoman.php
    Original file line number Diff line number Diff line change
    @@ -3,8 +3,8 @@
    * Converts decimal numbers to Roman numerials.
    * Limit [1; 3999]
    *
    * @param integer $n
    * @param bool $recursive
    * @param integer $n
    * @param bool $recursive
    * @return string
    */
    function decroman($n, $recursive = false) {
  2. fintara created this gist Jan 30, 2014.
    57 changes: 57 additions & 0 deletions DecimalToRoman.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    <?php
    /**
    * Converts decimal numbers to Roman numerials.
    * Limit [1; 3999]
    *
    * @param integer $n
    * @param bool $recursive
    * @return string
    */
    function decroman($n, $recursive = false) {
    if( !($n > 0 && $n < 4000))
    return;

    $roman = array(
    1 => 'I',
    4 => 'IV',
    5 => 'V',
    9 => 'IX',
    10 => 'X',
    40 => 'XL',
    50 => 'L',
    90 => 'XC',
    100 => 'C',
    400 => 'CD',
    500 => 'D',
    900 => 'CM',
    1000 => 'M',
    );

    if(array_key_exists($n, $roman))
    return $roman[$n];

    if($n < 10 || $n % 10 === 0 || $n % 100 === 0 || $n % 1000 === 0) {
    for($m = 1; $m <= 1000; $m *= 10) {
    for($i = 2; $i < 4; $i++)
    if($n / $m === $i)
    return str_repeat($roman[$n / $i], $i);

    for($i = 6; $i < 9; $i++)
    if($n / $m === $i)
    return $roman[$n - abs($i - 5) * $m] . decrom($n / $i * ($i - 5));
    }
    }

    if(!$recursive) {
    $roman = array();
    $roman = '';
    $ten = 1;
    do {
    $roman[] = decrom(($n % 10) * $ten, true);
    $n = (int) ($n / 10);
    $ten = $ten * 10;
    } while ($n > 0);

    return implode('', array_reverse($roman));
    }
    }