I'm seeing this in some code I'm working on:
num1 = (float)double.Parse(parameters[i + 1]);
num2 = (float)double.Parse(parameters[i + 2]);
Was wondering why they wouldn't just use float.Parse
instead of double.Parse
and casting to a float
. Is there a good reason?
Is there a good reason?
Yes. Above code will raise OverflowException
if parameter is big, but code expects only values with max value as float max.
Is there a good reason?
Not really. The main difference here would be:
A bit of extra overhead (which is of course not beneficial in any way)
A different potential exception if the value is outside of the range representable by a single.
In general, this likely should have just use Single.Parse directly.
If you try this code, you will see that if the number is, for instance, too big to be represented using float, it will raise an exception but when cast from double to float there won't be any Exceptions. the number will be infinity. Try it yourself:
string numString = "23339823498723948723958734956283468237468273468274602983409283.4092834092834029834029384029834";
double num2 = double.Parse(numString);
float num3 = (float)num2;
float num1 = float.Parse(numString);
Maybe someone expected this behavior at the first place. Even-though, I would use try catch instead of this approach.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.