Pick a Theme:
       
       

Converting to Roman Numerals
Web Script

October 13, 2011

Menu
Home

Outdoors (12)
Submit Comments (1)
Outdoors (3)
Food (19)
Erudition (12)
Projects (6)
Scouting (4)
Programming (5)
Art (4)
Bad math (9)
Mis-information (4)
Minecraft (4)
Random (12)

I wanted my counter down at the bottom to display the count in roman numerals. Now I *could* go hunt down the script, but I think I'll write my own. This is mostly because I need to learn accosiative arrays, and this is good time to force myself. The whole code is at the bottom, you don't have to piece everything together (I HATE that). Of course, now I want to make a script to go the other way :)

UPDATE - My wonderful friend Ashley took me at my word an used *any* number, she picked 1, 265, 457. That would be 1265 M's, and then the rest...oops. So I've added some *fake* roman numerals to prevent that. If you go even bigger than that I am not responsible for you computer screen disaster.

If all you want to do is play, here you go:

Number:
Roman Number:

The Script

At first I thought I could get away with the 7 letters, but then 4 (IV), 9 (IX), and those other numbers screwed it up. I also found out that you have to start at the biggest number and work downwards otherwise you get 700 million I's across the page :P...So now my array looks like this:

<?php
$temp 
$page_count
$values = array("M6+" => 1000000000"M5+" => 100000000"M4+" => 10000000,
                
"M3+" => 1000000"M2+" => 100000"M1+" => 10000,
                
"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);
?>

Well my standard for loop approach failed because of the keys (grrr), now I've had to learn foreach loops too. Well if I'm ever not able to sleep I can update all my old scripts...On the plus side I learned that I can use 'intval(blah)' instead of 'round(blah, 0)'.

<?php
//DOES NOT WORK!!! 
$values_size count($values); 
for (
$i=0$i<$vaules_size;$i++) { 
  
$multiples intval($temp $values[$i]); 
  
$display .= str_repeat($i$multiples); 
}
?>

This works however:

<?php
foreach ($values as $output => $number) { 
  
$multiples intval($temp $number); 
  
$display .= str_repeat($output$multiples); 
  
$temp $temp $number
}
?>

Ok, now to turn it into a function:

<?php
function to_roman_num($temp){ 
  
$values = array("M6+" => 1000000000"M5+" => 100000000"M4+" => 10000000,
                  
"M3+" => 1000000"M2+" => 100000"M1+" => 10000,
                  
"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 (
$values as $output => $number) { 
    
$multiples intval($temp $number); 
    
$display .= str_repeat($output$multiples); 
    
$temp $temp $number
  } 
  return 
$display
}
?>