The routines follow.
// Routine to convert a string to a double -- Allowed input is in fixed notation ddd.fff
// This does not use MathLib.
//
double strToDouble(CharPtr str)
{ Int i, start, length, punctPos;
double result, sign, fractPart;
WordPtr attributes;
result = fractPart = 0.0;
length = punctPos = StrLen(str);
attributes = GetCharAttr(); // get the attributes for IsDigit macro
start = 0;
sign = 1.0;
if (str[0] == '-')
{ sign = -1.0;
start = 1;
}
for (i=start; i<length; i++) // parse the string from left to right converting the integer part
{ if (str[i] != '.')
{ if (IsDigit(attributes, str[i]))
result = result * 10.0 + (str[i] - 0x30);
else { FrmAlert(ALERTID_ERROR);
return 0.0;
}
}
else { punctPos = i;
break;
}
}
if (str[punctPos] == '.') // parse the string from the end to the '.' converting the fractional part
{ for (i=length-1; i>punctPos; i--)
{ if (IsDigit(attributes, str[i]))
fractPart = fractPart / 10.0 + (str[i] - 0x30);
else { FrmAlert(ALERTID_ERROR);
return 0.0;
}
}
result += fractPart / 10.0;
}
return result * sign; // correcting the sign
}
// Routine to convert a string to a double --
// both fixed and scientific notation: ddd.fff and ddd.fffexx
// Requires MathLib but otherwise not much larger than strToDouble.
// This could be done much simpler with StrAToI but we lose line parse checking.
double strToDoubleScientific(CharPtr str)
{ Int i, start, length, punctPos, exponent, ePos;
double result, sign, fractPart;
CharPtr ePtr;
WordPtr attributes;
result = fractPart = 0.0;
length = punctPos = StrLen(str);
ePtr = StrStr(str, "e");
ePos = ePtr - str;
attributes = GetCharAttr(); // get the attributes for IsDigit macro
start = 0;
sign = 1.0;
if (str[0] == '-')
{ sign = -1.0;
start = 1;
}
for (i=start; i<length; i++) // parse the string from left to right converting the integer part
{ if (!(str[i] == '.' || str[i] == 'e'))
{ if (IsDigit(attributes, str[i]))
result = result * 10.0 + (str[i] - 0x30);
else { FrmAlert(ALERTID_ERROR);
return 0.0;
}
}
else { punctPos = i;
break;
}
}
if (str[punctPos] == '.') // parse the string from the end to the '.' converting the fractional part
{ if (ePtr) start = ePos;
else start = length;
for (i=start-1; i>punctPos; i--)
{ if (IsDigit(attributes, str[i]))
fractPart = fractPart / 10.0 + (str[i] - 0x30);
else { FrmAlert(ALERTID_ERROR);
return 0.0;
}
}
result += fractPart / 10.0;
}
exponent = 0;
if (ePtr) exponent = StrAToI(ePtr+1); // adjust the result for the exponent
return result * pow(10, exponent) * sign;
}
End of strToDoubleScientific()