Convert.ToInt32(float) fails when trying to convert float to Int32
Asked Answered
E

4

6

No exception is thrown, function just halts at this statement:

int productQuantity = Convert.ToInt32("1.00");

and returns.

What am I doing wrong to convert this float to Int32?

Note: I am running in a BackgroundWorkerThread.

Ergosterol answered 24/8, 2010 at 15:27 Comment(2)
That's a string, not a float.Litharge
@NullUserException: Yes, but I have converted before if it is just "1" without the decimals.Ergosterol
B
8

An exception is being thrown in this case it's just not being surfaced in the debugger. This string is not in a format that is convertible to an Int32 type and hence throws and exception. You can verify this by wrapping it in a try/catch block if the IDE isn't cooperating.

The best approach here is probably to convert the string to a double and then manually cast it down to an int. This does open the door for data loss due to precision differences. But given your input is in a float style format this is unavoidable if you want the final product to be an int

Bombacaceous answered 24/8, 2010 at 15:30 Comment(1)
+1 good points on the unsurfacable exception, easy to forget!Wavellite
R
6

You need to convert it to a double first, and then convert to Int32.

int productQuantity = Convert.ToInt32(double.Parse("1.00"));
Restricted answered 24/8, 2010 at 15:41 Comment(1)
with strings I recommend to always use TryParse, saves you a lot of trouble.Wavellite
E
2

An exception is thrown, it's just that to see it you have to inspect the RunWorkerCompletedEventArgs.Error property in the event handler for BackgroundWorker.RunWorkerCompleted.

Any exception that is thrown from the background worker's thread when the background work is being done is assigned to that property.

Ecliptic answered 24/8, 2010 at 15:36 Comment(0)
P
0

FormatException Input string was not in a correct format.

Poeticize answered 24/8, 2010 at 15:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.