Is there any use to using Math.Floor over explicit whole casts?

The question is pretty simple, is there any benefit or difference? I noticed that in C # the function returns double without any decimal places, while in java it stores decimal places, but other than that the result is the same.

Here is the code I used in Java and C #, and the output:

//Java //C# double a = 5.5; double a = 5.5; System.out.println(Math.floor(a)); Console.WriteLine(Math.Floor(a)); System.out.println((int)a); Console.WriteLine((int)a); //Output //Output 5.0 5 5 5 
+6
source share
1 answer

Yes , for negative numbers this works the opposite way.

Example (using the Mono C # csharp interactive shell):

 csharp> Math.Floor(-12.0d) -12 csharp> Math.Floor(-12.5d) -13 csharp> (int) -12.5 -12 

(the same for Java / C #), and I think most languages ​​are anyway.

Casting an integer floating-point number is done by discarding the decimal part that supports the integer part. The integer part of -12.5 is 12 . So negative numbers make a Math.Ceil if you convert it to int .

In addition, as @Matthew claims, a float or double can reach numbers like 1.023e23 (Avogadro constant). Just because the mantissa can no longer represent decimal digits. Numbers that are in any case considered integers but cannot be represented int . Performing the Math.floor operation, nothing happens, but the value is saved. Although converting to int can lead to overflow :

An example :

 csharp> double ac = 1.023e23; csharp> Math.Floor(ac); 1.023E+23 csharp> (int) ac; 0 

Note: this may look far, but nevertheless, there is a clear difference in semantics. The difference, which in any case leads to errors.

It also works differently for infinite numbers and NaN :

 System.out.println(Math.floor(Double.POSITIVE_INFINITY)); // Prints Infinity System.out.println((int)Double.POSITIVE_INFINITY); // Prints 2147483647 System.out.println(Math.floor(Double.NaN)); // Prints NaN System.out.println((int)Double.NaN); // Prints 0 

But I will always use them all the same. Casting makes things more unreadable. Rounding up / down / off is a bit of a side effect. Using Math.Ceil/Floor/Round , it is clear what you mean.

Sometimes integer casting is actually more efficient than performing a floor / ceiling operation. But an intelligent compiler can sometimes get that a variable will always store a positive number and, thus, optimize it itself. And besides, for most applications this will lead to a slight decrease in performance.

+15
source

Source: https://habr.com/ru/post/980328/


All Articles