Home>Article>Backend Development> How to convert integer numbers to Roman numerals in PHP? (code example)
How to convert an integer number to Roman numerals for display? The following article will show you how to use PHP to convert integer numbers to Roman numerals. I hope it will be helpful to you.
Method 1: Custom function
We can manually write a function to achieve this function , this function can take a number as the first argument, convert it to Roman and return it.
Note: Most algorithms only work in the range of 1-4999, if extremely large numbers are used, the script will fail.
Implementation code:
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) { // Look for number of matches $matches = intval($n / $value); // Concatenate characters $result .= str_repeat($roman, $matches); // Substract that from the number $n = $n % $value; } return $result; } echo '整数数字转换为罗马数字:
'; // VIII echo '数字8:'.numberToRoman(8).'
'; // CXXIII echo '数字123:'.numberToRoman(123).'
'; // MMCCCLV echo '数字2355:'.numberToRoman(2355).'
'; // MMMMCMXCIX echo '数字4999:'.numberToRoman(4999).'
'; ?>
Output:
##Method 2: Use Romans library
Romans library is a very simple PHP Roman numeral library that allows you to convert integers to their Roman representation and vice versa. Note: If you do not have this library, you need to install it first; after installing the Romans library, you can use its namespace and use functions that can help convert numbers. The Romans library contains a pair of simple filters for converting a string with Roman numerals into an int representing the input as decimal, and converting a decimal int into a string with Roman numerals as the result.1. Convert integers to Roman numerals
To convert integers to Roman representation, you need to use the IntToRoman class, create an instance and call the filter method from it. This method takes a number as the first parameter and returns a string with Roman numerals:filter(1999); echo $result; ?>Output:
MCMXCIX
2. Convert Roman numerals to integers
To convert Roman numerals to integer representation, you need to use the RomanToInt class, create an instance and call the filter method from it. This method takes a string using Roman numerals as the first parameter and returns an integer with a numeric value:filter('MCMXCIX'); echo $result; ?>Output:
1999Recommended related video tutorials: "
PHP Tutorial》
The above is the entire content of this article, I hope it will be helpful to everyone’s study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !The above is the detailed content of How to convert integer numbers to Roman numerals in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!