问题
How to apply floor function to float or double values to get integer.I got double Value:4.4497083717E10 float Value:4.4497084E10 out of my function.I got floor values as Floor of double:4.4497083717E10 Floor of float:4.4497084416E10.Is there a possibility that floor results in a integer??
回答1:
.Is there a possibility that floor results in a integer??
From a type perspective - no. Math.floor is declared to return a double
, and so will never return something with a static type of int
.
That said, the documentation for the method declares that the returned value is equal to an integer. So simply casting the returned result to an int
will always give you the output you expect.
(That is, assuming your result is in range. A double
can hold larger numbers that an int
can represent. Check out Narrowing primitive conversions for the technical details. You may want to bounds-check your data to ensure it's always sensible to convert to int
.)
回答2:
4.4497083717E10 is too large to be an int
, you would have to cast to a long
.
Casting to a long keeps the whole portion of the double making it the same as Math.floor
for values which can be represented as a long. i.e.
long l = (long) Math.floor(4.4497083717E10);
is the same as
long l = (long) 4.4497083717E10;
System.out.println((int) Math.floor(4.4497083717E10));
System.out.println((long) Math.floor(4.4497083717E10));
System.out.println((long) 4.4497083717E10);
prints
2147483647 -- due to an overflow
44497083717
44497083717
来源:https://stackoverflow.com/questions/10243613/floor-function-to-float-and-double-values