যদি আপনার কাছে দৃ strong় সন্দেহ থাকে যে ডাবলটি আসলে একটি দীর্ঘ, এবং আপনি এটি করতে চান
1) দীর্ঘ হিসাবে এর সঠিক মানের একটি হ্যান্ডেল পান
2) কোনও ত্রুটি যখন এটি দীর্ঘ না হয় তখন নিক্ষেপ করুন
আপনি এই জাতীয় কিছু চেষ্টা করতে পারেন:
public class NumberUtils {
/**
* Convert a {@link Double} to a {@link Long}.
* Method is for {@link Double}s that are actually {@link Long}s and we just
* want to get a handle on it as one.
*/
public static long getDoubleAsLong(double specifiedNumber) {
Assert.isTrue(NumberUtils.isWhole(specifiedNumber));
Assert.isTrue(specifiedNumber <= Long.MAX_VALUE && specifiedNumber >= Long.MIN_VALUE);
// we already know its whole and in the Long range
return Double.valueOf(specifiedNumber).longValue();
}
public static boolean isWhole(double specifiedNumber) {
// http://stackoverflow.com/questions/15963895/how-to-check-if-a-double-value-has-no-decimal-part
return (specifiedNumber % 1 == 0);
}
}
লং হ'ল ডাবলের একটি উপসেট, তাই আপনি অজান্তে লং এর সীমার বাইরে থাকা একটি ডাবলকে রূপান্তর করার চেষ্টা করলে আপনি কিছু অদ্ভুত ফলাফল পেতে পারেন:
@Test
public void test() throws Exception {
// Confirm that LONG is a subset of DOUBLE, so numbers outside of the range can be problematic
Assert.isTrue(Long.MAX_VALUE < Double.MAX_VALUE);
Assert.isTrue(Long.MIN_VALUE > -Double.MAX_VALUE); // Not Double.MIN_VALUE => read the Javadocs, Double.MIN_VALUE is the smallest POSITIVE double, not the bottom of the range of values that Double can possible be
// Double.longValue() failure due to being out of range => results are the same even though I minus ten
System.out.println("Double.valueOf(Double.MAX_VALUE).longValue(): " + Double.valueOf(Double.MAX_VALUE).longValue());
System.out.println("Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + Double.valueOf(Double.MAX_VALUE - 10).longValue());
// casting failure due to being out of range => results are the same even though I minus ten
System.out.println("(long) Double.valueOf(Double.MAX_VALUE): " + (long) Double.valueOf(Double.MAX_VALUE).doubleValue());
System.out.println("(long) Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + (long) Double.valueOf(Double.MAX_VALUE - 10).doubleValue());
}
myLong == (long)(myDouble + 1)যেখানেmyLongসমানmyDoubleনির্ণয় করা হবেtrue