darkflib.github.io

Site Reliability Team Lead at News UK

View on GitHub
13 March 2011

Romannumerals

by Mike

I needed a function to convert dates to their Roman numeric equivalents. The rules are pretty easy to understand so I thought I’d knock up a function.

function numerals($num) {
//You are free to use this function under a BSD license
//essentially cost free, no code taint,
//but you must leave my copyright in.
//(c)MMXI Mike Preston mikepreston.org
$out='';
while ($num > 0) {
    if ($num >= 1000) {
        $out.='M';
        $num=$num - 1000;
    } else if ($num >= 900) {
        $out.='CM';
        $num=$num - 900;
    } else if ($num >= 500) {
        $out.='D';
        $num=$num - 500;
    } else if ($num >= 400) {
        $out.='CD';
        $num=$num - 400;
    } else if ($num >= 100) {
        $out.='C';
        $num=$num - 100;
    } else if ($num >= 90) {
        $out.='XC';
        $num=$num - 90;
    } else if ($num >= 50) {
        $out.='L';
        $num=$num - 50;
    } else if ($num >= 40) {
        $out.='XL';
        $num=$num - 40;
    } else if ($num >= 10) {
        $out.='X';
        $num=$num - 10;
    } else if ($num >= 9) {
        $out.='IX';
        $num=$num - 9;
    } else if ($num >= 5) {
        $out.='V';
        $num=$num - 5;
    } else if ($num >= 4) {
        $out.='IV';
        $num=$num - 4;
    } else {
        $out.='I';
        $num=$num - 1;
    }
}
return $out;
}

Test Code

echo "<pre>Test Start\n";
echo numerals(1) . " - 1\n";
echo numerals(4) . " - 4\n";
echo numerals(5) . " - 5\n";
echo numerals(9) . " - 9\n";
echo numerals(10) . " - 10\n";
echo numerals(40) . " - 40\n";
echo numerals(50) . " - 50\n";
echo numerals(90) . " - 90\n";
echo numerals(100) . " - 100\n";
echo numerals(400) . " - 400\n";
echo numerals(500) . " - 500\n";
echo numerals(900) . " - 900\n";
echo numerals(1000) . " - 1000\n";
echo numerals(2000) . " - 2000\n";
echo numerals(1999) . " - 1999\n";
echo numerals(2001) . " - 2001\n";
echo numerals(2010) . " - 2010\n";
echo numerals(2011) . " - 2011\n";

echo "Test End\n";

?>
tags: