为什么 Math.Floor(Double) 返回 Double 类型的值?
我需要从小数或双精度数中获取左侧整数值。例如:我需要从 4.6 中获取值 4。我尝试使用 Math.Floor 函数,但它返回一个双精度值,例如:它从 4.6 返回 4.0。 MSDN 文档说它返回一个整数值。我在这里错过了什么吗?或者有不同的方法来实现我正在寻找的东西吗?
I need to get the left hand side integer value from a decimal or double. For Ex: I need to get the value 4 from 4.6. I tried using Math.Floor function but it's returning a double value, for ex: It's returning 4.0 from 4.6. The MSDN documentation says that it returns an integer value. Am I missing something here? Or is there a different way to achieve what I'm looking for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
double
的范围比int
或long
的范围宽得多。考虑这段代码:整数超出了 long 的范围 - 那么您期望发生什么?
通常,您知道该值实际上在
int
或long
的范围内,因此您对其进行强制转换:但该强制转换的责任是由开发人员负责,而不由
Math.Floor
本身负责。如果所有超出long
范围的值都出现异常,那么它就会失败,这是不必要的限制。The range of
double
is much wider than the range ofint
orlong
. Consider this code:The integer is outside the range of
long
- so what would you expect to happen?Typically you know that the value will actually be within the range of
int
orlong
, so you cast it:but the onus for that cast is on the developer, not on
Math.Floor
itself. It would have been unnecessarily restrictive to make it just fail with an exception for all values outside the range oflong
.根据 MSDN,Math.Floor(double) 返回双精度: http://msdn .microsoft.com/en-us/library/e0b5f0xb.aspx
如果您希望将其作为 int:
我可以看到 MSDN 文章如何具有误导性,但他们应该指定虽然结果是“整数” (在本例中表示整数)它仍然是 TYPE Double
According to MSDN, Math.Floor(double) returns a double: http://msdn.microsoft.com/en-us/library/e0b5f0xb.aspx
If you want it as an int:
I can see how the MSDN article can be misleading, they should have specified that while the result is an "integer" (in this case meaning whole number) it is still of TYPE Double
如果您只需要数字的整数部分,请将数字转换为
int
。这将截断小数点处的数字。If you just need the integer portion of a number, cast the number to an
int
. This will truncate the number at the decimal point.Floor 将其保留为双精度,因此您可以用它进行更多双精度计算。
如果您希望将其作为 int,请将 Floor 的结果强制转换为 int。
不要将原始 double 转换为 int,因为对于负数,下限规则是不同的 (IIRC)。
Floor leaves it as a double so you can do more double calculations with it.
If you want it as an int, cast the result of floor as an int.
Don't cast the original double as an int because the rules for floor are different (IIRC) for negative numbers.
如果您采用
4.6
它返回4
作为输出,这将为您提供您想要的确切值。This will give you the exact value what you want like if you take
4.6
it returns4
as output.