CFLib.org – Common Function Library Project

romanToDecimal(input)

Last updated February 4, 2010

Version: 2 | Requires: ColdFusion 5 | Library: StrLib

 
Rated 0 time(s). Average Rating: 0

Description:
Converts Roman numerals to decimal. Assumes a valid ROman numeral.

Return Values:
Returns a number.

Example:

view plain print about
<cfset inputs = "XX,XI,IV,VIII,MC,DL,XL">
<cfloop index="input" list="#inputs#">
    <cfoutput>
    #input#=#romantodec(input)#<br/>
    </cfoutput>
</cfloop>

Parameters:

Name Description Required
input Roman number input. Yes

Full UDF Source:

view plain print about
<cfscript>
/**
 * Converts Roman numerals to decimal.
 * v2 fix by for non standard things like IIX, fix done by Gary Funk
 * 
 * @param input      Roman number input. (Required)
 * @return Returns a number. 
 * @author Raymond Camden (ray@camdenfamily.com) 
 * @version 2, February 4, 2010 
 */

function romantodec(input) {
    var romans = {};
    var result = 0;
    var pos = 1;
    var char = "";
    var thisSum = "";
    var nextchar = "";
    var subSum = 0;
        
    romans["I"] = 1;
    romans["V"] = 5;
    romans["X"] = 10;
    romans["L"] = 50;
    romans["C"] = 100;
    romans["D"] = 500;
    romans["M"] = 1000;

    while(pos lte len(input)) {
        char = mid(input, pos, 1);
        subSum += romans[char];
        if(pos != len(input)) {
            nextchar = mid(input, pos + 1, 1);
            if(romans[char] == romans[nextchar]) {
                pos++;
            } else if(romans[char] 
< romans[nextchar]) {
                result = result + romans[nextchar] - subSum;
                subSum = 0;
                pos += 2;
            } else {
                result = result + subSum;
                subSum = 0;
                pos++;
            }
        } else {
            result = result + subSum;
            pos++;
        }
    }    
    return result;
}
</cfscript>
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Tayo Akinmade Tayo Akinmade added
arrayTrim
3 day(s) ago

Will Belden Will Belden added
longTime
9 day(s) ago

James Sleeman James Sleeman added
quickSort
19 day(s) ago

Ben Forta Ben Forta added
GetHostAddress
22 day(s) ago

Top Rated

Darwan Leonardo Sitepu EksporSQLData
Rated 5.0, 16 time(s)

Darwan Leonardo Sitepu backupDatabase
Rated 5.0, 13 time(s)

Barney Boisvert indentXml
Rated 5.0, 10 time(s)

Kevin Pepperman generateSsccAsn
Rated 5.0, 4 time(s)

Created by Raymond Camden / Design by Justin Johnson