On 28 Nov 2006 07:51:06 -0800,
ga********@myway.com wrote:
>This would rely on the garbage text that proceeds the number always
being in the same format.
I think it would be better to convert the string to a character array
and examine each character for numeric validity before adding it to the
formatted string and parsing this as a double.
I've had a go but as people familliar to this forum may know, i'm a
complete beginner. My code doesn't work as it stands, perhaps someone
could offer a modification?
private void button1_Click(object sender, EventArgs e)
{
string somestring = "? 20.00";
char[] stringarray = somestring.ToCharArray();
string formattedstring = "0";
foreach (char c in stringarray)
{
if (((int)c >= 0 && (int)c <= 9) || c == '.')
{
formattedstring += c;
}
else
{
break;
}
}
double myDouble = double.Parse(formattedstring);
MessageBox.Show(myDouble.ToString());
}
Gary.;
First problem: When you enter your foreach loop, the first character
is '?', which activates the break; thus terminating the loop having
only processed one character. Remove the else part entirely as you
want to process all the characters in stringarray.
When you try this, you will find that it still does not work as you
expected.
Second problem: Your if statement starts:
if (((int)c >= 0 && (int)c <= 9) || c == '.')
When c = '2', (int)c is not 2, but the UTF encoding for 2. Change the
if to read:
if ((c >= '0' && c <= '9') || c == '.')
You did this correctly with the decimal point.
Your code now works after a fashion, though "20.02" would be a better
test number than 20.00. Try it to see why.
You ought to try running your code in the debugger. I just put one
breakpoint at the strat of the foreach loop, which found both your
problems easily.
Other points you may need to consider.
1 C# strings are immutable, you cannot change them. All you can do is
replace the old copy of the string with the new version. Better in
general to use a stringbuilder rather than a string in cases such as
this, where you do not know how long the final string is going to be.
2 Some countries use other characters such as ',' instead of '.' as a
decimal separator. Have a look at
System.Globalization.NumberFormatInfo.NumberDecima lSeparator.
3 You have no protection against a string like:
"? 20.02 ? 20.02 ? 20.03"
Try it and see what happens.
As a learning exercise you might also want to try writing a finite
state machine to parse real numbers out of a text string. It makes an
interesting little exercise.
rossum