CFLib.org – Common Function Library Project

romanToDecimal(input)

Last updated February 05, 2010

author

Raymond Camden

Version: 2 | Requires: CF5 | Library: StrLib

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

Return Values:
Returns a number.

Example:

<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:

/**
 * 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;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson