Why does Math.Floor(Double) return a value of type Double?

后端 未结 6 579
一生所求
一生所求 2020-12-10 10:22

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

相关标签:
6条回答
  • 2020-12-10 10:28

    That is correct. Looking at the declaration, Math.Floor(double) yields a double (see http://msdn.microsoft.com/en-us/library/e0b5f0xb.aspx). I assume that by "integer" they mean "whole number".

    0 讨论(0)
  • 2020-12-10 10:31

    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.

    double myDouble = 4.6;
    int myInteger = (int)myDouble;
    0 讨论(0)
  • 2020-12-10 10:37
    Convert.ToInt32(Math.Floor(Convert.ToDouble(value)))
    

    This will give you the exact value what you want like if you take 4.6 it returns 4 as output.

    0 讨论(0)
  • 2020-12-10 10:39

    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.

    0 讨论(0)
  • 2020-12-10 10:41

    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:

    int result = (int)Math.Floor(yourVariable);
    

    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

    0 讨论(0)
  • 2020-12-10 10:49

    The range of double is much wider than the range of int or long. Consider this code:

    double d = 100000000000000000000d;
    long x = Math.Floor(d); // Invalid in reality
    

    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 or long, so you cast it:

    double d = 1000.1234d;
    int x = (int) Math.Floor(d);
    

    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 of long.

    0 讨论(0)
提交回复
热议问题