Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

math

floor

People also ask

Why does the Math floor have a double return?

It's for precision. The double data-type has a 53 bit mantissa. Among other things that means that a double can represent all whole up to 2^53 without precision loss. If you store such a large number in an integer you will get an overflow.

Why does Java floor return double?

floor() returns the double value that is less than or equal to the argument and is equal to the nearest mathematical integer. Note: If the argument is Integer, then the result is Integer. If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

What type does Math floor return?

The Math. floor() function returns the largest integer less than or equal to a given number.

What happens when you use the Math floor and the result is equally close to two integers?

If two double values that are mathematical integers are equally close, the result is the integer value that is even. Special cases: If the argument value is already equal to a mathematical integer, then the result is the same as the argument.


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.


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


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;