BetaDesigns( Blog ) Flex and Component Development

27Jan/093

Number Romanizer

I was messing around on a personal project today and had to build a simple converter to change numbers into Roman Numerals. Below is the result. Had a few issues trying to use a simple object to hold the numerals as ActionScript was sorting the object Alphabetically which meant I was getting false results especially with 4's which would return four 'I''s instead of the correct 'IV'.

 
/**
* Function that turns any number into it's roman numeral
* equivelant.
* We have to use an array to hold the values as if we use
* a Dictionary / Object actionScript sorts it alphabetically.
* and we don't get the correct results.
*
* @param value : Number 0 - 9999;
*/
public static function romanize( value : Number ) : String
{
var numerals : Array = [
{ label : 'M', value : 1000 },
{ label : 'CM', value : 900 },
{ label : 'D', value : 500 },
{ label : 'CD', value : 400 },
{ label : 'C', value : 100 },
{ label : 'XC', value : 90 },
{ label : 'L', value : 50 },
{ label : 'XL', value : 40 },
{ label : 'X', value : 10 },
{ label : 'IX', value : 9 },
{ label : 'V', value : 5 },
{ label : 'IV', value : 4 },
{ label : 'I', value : 1 }
]
 
var roman : String = '';
 
for( var i : String in numerals )
{
while( value >= numerals[ i ].value )
{
roman += numerals[ i ].label;
value -= numerals[ i ].value;
}
}
 
return roman;
}
Be Sociable, Share!
Comments (3) Trackbacks (0)
  1. You forgot L and messed up XL/X

  2. …and it will fail for values >= 2000 and values ending with 2,3,7 and 8 (you need to repeat those M’s and I’s)

  3. Thanks for the info, I didn’t copy it over correctly :( as for the values not ending with 2,3,7 and 8 or being above 2000 can you give an example number? I have tried lots of different combinations and they all seem to work for me.
    Thanks
    Anthony


Leave a comment

(required)

No trackbacks yet.