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

前端 未结 4 977
情话喂你
情话喂你 2021-01-18 11:38

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

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

and returns.

What

4条回答
  •  太阳男子
    2021-01-18 12:05

    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

提交回复
热议问题