Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Floor vs cast to an integral type in C#

Tags:

Are there any reasons one would prefer to use Math.Floor vs casting to an integral type?

double num; double floor = Math.Floor(num); 

OR

double num; long floor = (long)num; 
like image 584
Zaid Masud Avatar asked Mar 21 '12 10:03

Zaid Masud


People also ask

Is int the same as math floor?

Cast to int is a function to convert variable of any datatype to integer type, on the other hand Math. floor function will only floor the decimal number to integer not converting datatype. But result will be different in case of negative values because Cast to Int approaches to zero and Math.

Does Math floor return an int?

The Java Math floor() is a mathematical function available in Java Math Library. This function returns the closest integer value (represented as a double value) which is less than or equal to the given double value.

What does the floor () method do?

Floor() is a Math class method. This method is used to find the largest integer, which is less than or equal to the passed argument.

What does casting to an int do?

Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.


2 Answers

There are some differences between casting to an integral type and using Math.Floor:

  1. When casting to an integral type, you'll end up with an integral type (obviously). So if you want to keep the number as a double, using Floor is easier.
  2. As a consequence of 1, casting will not work correctly if the given number is too large to be represented by the given integral type (a double can represent much larger numbers than a long).
  3. Floor rounds towards negative infinity. Casting rounds towards zero.
like image 101
sepp2k Avatar answered Nov 09 '22 12:11

sepp2k


It differs for negative values:

double num = -1.3; double floor = Math.Floor(num); // = -2 long cast = (long)num; // = -1 
like image 23
Daniel Hilgarth Avatar answered Nov 09 '22 13:11

Daniel Hilgarth