Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Converting roman notation to a numeric value

Title: Converting roman notation to a numeric value Question: Carlos Alberto Longen wrote a nice article on converting a numeric value into roman notation. This is the complement function, going the other way. Minor update: arranging the items of the case statement in ASCII order makes it slightly faster. Inc and Dec also improves speed a little (not that it really is needed, but it looks better...) Answer: function RomanToDec(const Value:string):integer; var i,lastValue,curValue:integer; begin Result := 0; lastValue := 0; for i := Length(Value) downto 1 do begin case UpCase(Value[i]) of 'C': curValue := 100; 'D': curValue := 500; 'I': curValue := 1; 'L': curValue := 50; 'M': curValue := 1000; 'V': curValue := 5; 'X': curValue := 10; else raise Exception.CreateFmt('Invalid character: %s',[Value[i]]); end; if curValue Dec(Result,curValue) else Inc(Result,curValue); lastValue := curValue; end; end;