Conversion from Long to Double in Java

前端 未结 8 418
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 01:07

Is there any way to convert a Long data type to Double or double?

For example, I need to convert 15552451L to a

相关标签:
8条回答
  • 2021-01-31 01:22

    Simple casting?

    double d = (double)15552451L;
    
    0 讨论(0)
  • 2021-01-31 01:24
    Long i = 1000000;
    String s = i + "";
    Double d = Double.parseDouble(s);
    Float f = Float.parseFloat(s);
    

    This way we can convert Long type to Double or Float or Int without any problem because it's easy to convert string value to Double or Float or Int.

    0 讨论(0)
  • 2021-01-31 01:36

    As already mentioned, you can simply cast long to double. But be careful with long to double conversion because long to double is a narrowing conversion in java.

    Conversion from type double to type long requires a nontrivial translation from a 64-bit floating-point value to the 64-bit integer representation. Depending on the actual run-time value, information may be lost.

    e.g. following program will print 1 not 0

        long number = 499999999000000001L;
        double converted = (double) number;
        System.out.println( number - (long) converted);
    
    0 讨论(0)
  • 2021-01-31 01:40

    You can try something like this:

    long x = somevalue;
    
    double y = Double.longBitsToDouble(x);
    
    0 讨论(0)
  • 2021-01-31 01:41

    Are you looking for the binary conversion?

    double result = Double.longBitsToDouble(15552451L);
    

    This will give you the double with the same bit pattern as the long literal.

    Binary or hexadecimal literals will come in handy, here. Here are some examples.

    double nan = Double.longBitsToDouble(0xfff0000000000001L);
    double positiveInfinity = Double.longBitsToDouble(0x7ff0000000000000L);
    double positiveInfinity = Double.longBitsToDouble(0xfff0000000000000L);
    

    (See Double.longBitsToDouble(long))

    You also can get the long back with

    long bits = Double.doubleToRawLongBits(Double.NaN);
    

    (See Double.doubleToRawLongBits(double))

    0 讨论(0)
  • 2021-01-31 01:43

    What do you mean by a long date type?

    You can cast a long to a double:

    double d = (double) 15552451L;
    
    0 讨论(0)
提交回复
热议问题