Php decimal to Roman number Conversion
- 8 Comment
![]()
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; } ?>
8 Comments on this post
Trackbacks
-
Geoserv said:
STUMBLED!
Sweet, good post.
VOTED for you at:
http://www.newsdots.com/tutorials/php-decimal-to-roman-number-conversion-programming-ideas-logics-tips-and-tricks-sajithmr-com/April 18th, 2008 at 11:57 pm -
NasirJumani said:
Cute little trick, stumbled!
April 20th, 2008 at 7:35 pm -
alex said:
Also doesn’t really work:
9 will come out as viiii instead of ix.May 26th, 2008 at 3:50 am -
Sajith M.R said:
@Alex
That might be your mistake. I tried 9 and i got IX as output.
The function is right.Regards
SajithMay 26th, 2008 at 12:39 pm -
alex said:
Oh yes, you’re right, good shout, didn’t read it properly first time.
May 26th, 2008 at 3:06 pm -
Djordje said:
“private” modifier is useless outside of a class
June 11th, 2008 at 5:38 pm -
JonsJava said:
Nice to see you steal stuff from other websites. Too bad you forgot to copy and paste the whole thing.
April 22nd, 2009 at 12:44 am -
Borellus said:
Nice little function there, I think I may try to use it at some point.
June 28th, 2009 at 4:11 pm
