I am writing a library for our company\'s product that will take any kind of architectural dimension that our users are already familiar with as input for a function that conver
This function works for your input value examples.
public static Double Conv(String inp)
{
String expr= "((?\\d+)(?\\d{2})(?\\d{2}))|((?[\\d.]+)')?[\\s-]*((?\\d+)?[\\s-]*((?\\d+)/(?\\d+))?\")?";
Match m = new Regex(expr).Match(inp);
Double feet = m.Groups["feet"].Success ? Convert.ToDouble(m.Groups["feet"].Value) : 0;
Int32 inch = m.Groups["inch"].Success ? Convert.ToInt32(m.Groups["inch"].Value) : 0;
Int32 sixt = m.Groups["sixt"].Success ? Convert.ToInt32(m.Groups["sixt"].Value) : 0;
Int32 numer = m.Groups["numer"].Success ? Convert.ToInt32(m.Groups["numer"].Value) : 0;
Int32 denom = m.Groups["denom"].Success ? Convert.ToInt32(m.Groups["denom"].Value) : 1;
return feet*12+inch+sixt/16.0+numer/Convert.ToDouble(denom);
}
Please note that I haven't made any effort in testing other inputs than the valid ones you supplied. You may want to e.g. check for Success in at least some of the capture groups, or maybe do validation as a separate step. This code was made with parsing in mind.
Edit:
Here is a more robust version:
public static Double Conv(String inp)
{
String expr= "^\\s*(?-)?\\s*(((?\\d+)(?\\d{2})(?\\d{2}))|((?[\\d.]+)')?[\\s-]*((?\\d+)?[\\s-]*((?\\d+)/(?\\d+))?\")?)\\s*$";
Match m = new Regex(expr).Match(inp);
if(!m.Success || inp.Trim()=="")
{
// maybe throw exception or set/return some failure indicator
return 0; // here using return value zero as failure indicator
}
Int32 sign = m.Groups["minus"].Success ? -1 : 1;
Double feet = m.Groups["feet"].Success ? Convert.ToDouble(m.Groups["feet"].Value) : 0;
Int32 inch = m.Groups["inch"].Success ? Convert.ToInt32(m.Groups["inch"].Value) : 0;
Int32 sixt = m.Groups["sixt"].Success ? Convert.ToInt32(m.Groups["sixt"].Value) : 0;
Int32 numer = m.Groups["numer"].Success ? Convert.ToInt32(m.Groups["numer"].Value) : 0;
Int32 denom = m.Groups["denom"].Success ? Convert.ToInt32(m.Groups["denom"].Value) : 1;
return sign*(feet*12+inch+sixt/16.0+numer/Convert.ToDouble(denom));
}
It fails for empty strings, and strings with extra characters other than allowed by your examples. Five or more digits are treated as the simpler format.
The changes are the begin- and end anchors and allowed leading and trailing whitespace, as well as the special case check for emtpy/whitespace-only string in the if statement.
Disclaimer: this has obviously not been tested for every possible illegal input, and I am not a c# programmer anyway :-)