आप एक मजबूत संदेह है कि डबल वास्तव में एक लंबा है, और आप चाहते हैं
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());
}
स्रोत
2015-05-04 07:22:36
बस सुनिश्चित करें कि आप डबल्स अधिक से अधिक 2^54 या संख्या में [अंश] फ़िट नहीं होगा के साथ काम नहीं करते (http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3), इसलिए उदाहरण के लिए 'myLong == (long) (myDouble + 1)' जैसे अभिव्यक्तियां ' myLong' बराबर 'myDouble'' सत्य ' –
का मूल्यांकन करेगा इस विधि ('Double.longValue();') अभी भी उपयोगी है यदि आपके पास इस' ArrayList 'जैसी सरणीसूची जैसी चीज़ों से दोहरे मान हैं, तो आपको एक मिल जाएगा त्रुटि नहीं डाली जा सकती है। मैं बस यह किसी के लिए कह रहा हूं जो यहां आया था और थोड़ा अलग समस्या थी। –
SARose
आपका शीर्षक "डबल से लम्बा रूपांतरण" सही नहीं है, आपके प्रश्न को "लंबे से दोहरे रूपांतरण" शीर्षक की आवश्यकता है। –