Loss of precision - int -> float or double

后端 未结 9 1532
小蘑菇
小蘑菇 2020-11-27 15:22

I have an exam question I am revising for and the question is for 4 marks.

\"In java we can assign a int to a double or a float\". Will this ever lose

9条回答
  •  攒了一身酷
    2020-11-27 15:51

    Here's what JLS has to say about the matter (in a non-technical discussion).

    JLS 5.1.2 Widening primitive conversion

    The following 19 specific conversions on primitive types are called the widening primitive conversions:

    • int to long, float, or double
    • (rest omitted)

    Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision -- that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode.

    Despite the fact that loss of precision may occur, widening conversions among primitive types never result in a run-time exception.

    Here is an example of a widening conversion that loses precision:

    class Test {
             public static void main(String[] args) {
                    int big = 1234567890;
                    float approx = big;
                    System.out.println(big - (int)approx);
            }
    }
    

    which prints:

    -46
    

    thus indicating that information was lost during the conversion from type int to type float because values of type float are not precise to nine significant digits.

提交回复
热议问题