Search code examples
javafloating-point

Is Cast double of float always same in the Java?


Suppose we have a java float defined as float p = 4.423, will we always get same double value whenever double q =(double) p for the variable in the application flow, whenever it is cast as double? Suppose there is another place, where I am accessing the variable double r = (double) p. Will r be always equal to q?


Solution

  • The Java Language Specification, Java SE 21 Edition, §5.5 "Casting Contexts" specifies the conversions that a cast can perform. In the case of a conversion from float to double, the only one that's applicable is "a widening primitive conversion". §5.1.2 "Widening Primitive Conversion" specifies that "A widening primitive conversion does not lose information about the overall magnitude of a numeric value in the following cases, where the numeric value is preserved exactly", where one of the cases that it lists is "from float to double".

    So every cast from a given float to a double must preserve the value of the float exactly, which in turn means it must give the same value every time. (Disclaimer: I'm not sure if that applies to NaN values, which aren't exactly "numeric values" and in any case aren't equal to themselves. But at least for a "normal" value like your example of float p = 4.423, we don't need to worry about that.)