简体   繁体   English

为什么使用double.Parse然后转换为浮点数?

[英]Why use double.Parse and then cast to a float?

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 . 想知道为什么他们不会只使用float.Parse而不是double.Parse并且转换为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. 如果参数很大,上面的代码将引发OverflowException ,但代码只需要max值为float max的值。

Is there a good reason? 有充分的理由吗?

Not really. 并不是的。 The main difference here would be: 这里的主要区别是:

  1. A bit of extra overhead (which is of course not beneficial in any way) 一点额外的开销(这当然对任何方式都没有好处)

  2. 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. 一般来说,这可能应该直接使用Single.Parse

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. 如果您尝试使用此代码,您将看到如果该数字太大而无法使用float表示,则会引发异常,但是当从double转换为float时,将不会有任何异常。 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. 尽管如此,我会使用try catch而不是这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM