Jul 10 2007

Php decimal to Roman number Conversion

Decimal to Roman Number

In many cases, we , php programmers need Roman number display I II III IV etc.

Here is a simple algorithm for that .

<?php
 
// A function to return the Roman Numeral, given an integer
private 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;
}
 
?>

TAGS:

8 Comments on this post

Trackbacks

  1. Geoserv said:
  2. NasirJumani said:

    Cute little trick, stumbled!

    April 20th, 2008 at 7:35 pm
  3. alex said:

    Also doesn’t really work:
    9 will come out as viiii instead of ix.

    May 26th, 2008 at 3:50 am
  4. Sajith M.R said:

    @Alex
    That might be your mistake. I tried 9 and i got IX as output.
    The function is right.

    Regards
    Sajith

    May 26th, 2008 at 12:39 pm
  5. alex said:

    Oh yes, you’re right, good shout, didn’t read it properly first time.

    May 26th, 2008 at 3:06 pm
  6. Djordje said:

    “private” modifier is useless outside of a class

    http://www.free-circuit-diagrams.com

    June 11th, 2008 at 5:38 pm
  7. JonsJava said:

    Nice to see you steal stuff from other websites. Too bad you forgot to copy and paste the whole thing.

    http://www.go4expert.com/forums/showthread.php?t=4948

    April 22nd, 2009 at 12:44 am
  8. Borellus said:

    Nice little function there, I think I may try to use it at some point.

    June 28th, 2009 at 4:11 pm

LEAVE A COMMENT

Subscribe Form

Subscribe to Blog

Recent Comments

  • Sajith M.R: Press shift and enter key for a new line in chat
  • Borellus: Nice little function there, I think I may try to use it at some point.
  • Abhishek: Can we have newline characters…. i want something like this Line 1 Line 2 Line 3
  • Joanne Cox: Thanks for sharing this; your input is appreciated and has made me change my opinion slightly. About the...
  • Saboor: hi i also want to implement a chatting like Gmail or FaceBook , please, email me the source code on...

Recent Posts