phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - Number: Converting Numbers into Roman Numerals

Tag: number, convert, roman numerals   Category: PHP Application, PHP Basic
post: 16 Mar 2008 read: 246


PHP Number Tips - Part 6: If you want to print a number as a Roman Numeral, you only have to use PEAR's Numbers_Roman class such as:

<?php
//include Numbers_Roman class
include "Numbers/Roman.php";

//create object
$nr = new Numbers_Roman();

//result: "5 in Roman is V."
echo "5 in Roman is " . $nr->toNumeral(5) . ".\n";

//result: "318 in Roman is CCCXVIII".
echo "318 in Roman is " . $nr->toNumeral(318) . ".";
?>

The PEAR Number_Roman class translates regular numbers into their Roman equivalents. The class' toNumeral( ) method accepts an integer and outputs the corresponding Roman numeral. You can print a series of Roman numerals by combining the toNumeral( ) method with a loop, as shown here:


<?php
//include Numbers_Roman class
include "Numbers/Roman.php";

//create object
$nr = new Numbers_Roman();

//print numbers 1 to 100 as Roman numerals
//result: "I II III IV...XCVIII XCIX C"
foreach (range(1, 100) as $x) {
  print $nr->toNumeral($x) . " ";
}
?>

You can also reverse the process with the toNumber( ) method as in the following code snippet:


<?php
//include Numbers_Roman class
include "Numbers/Roman.php";

//create object
$nr = new Numbers_Roman();

//print CVII as an Arabic number
//result: "CVII = 107"
echo "CVII = " . $nr->toNumber('CVII');
?>

Note that toNumeral( ) does not support decimal or negative values.




| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


619
posting