I have a method returning long
and there are cases where a valid result can not be computed. Double
has the NaN
constant, which is not expressable in long
.
I can think of two solutions:
double
, check for NaN and convert to long
if everything is fine.Is either preferrable / more "Javanic"? Are there other ways / Did I miss something obvious?
No, NaN is a floating point value. Every possible value of an int is a number.
“NaN” stands for “not a number”. “Nan” is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined.
In mathematics, taking the square root of a negative number results in an imaginary number. This case is dealt with by returning NaN in Java. Taking mod of a number with zero, will return the remainder after dividing a value by zero. Hence, NaN is returned.
isNaN() method in Float Class is a built in method in Java returns true if this Float value or the specified float value is Not-a-Number (NaN), or false otherwise. Parameters: he function accepts a single parameter val which specifies the value to be checked when called directly with the Float class as static method.
You can make the return-type Long
(the boxed version of long
) and return null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With