Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8154433

Add Math.toLongExact(double) and Math.toDoubleExact(long)

    XMLWordPrintable

Details

    Description

      A DESCRIPTION OF THE REQUEST :
      Add the following methods to java.lang.math:

        public static long toLongExact(double x)
        public static double toDoubleExact(long x)

      These methods would throw ArithmeticException if the argument cannot be exactly represented using the return type, or else they would cast the argument to the return type.

      Examples:

        toLongExact(0.0) ---> ok
        toLongExact(-0.0) ---> error
        toLongExact(Double.NaN) ---> error
        toLongExact(Double.POSITIVE_INFINITY) ---> error
        toLongExact(Double.NEGATIVE_INFINITY) ---> error
        toLongExact(0x1p63) ---> error
        toLongExact(-0x1p63) ---> ok

        toDoubleExact(0L) ---> ok
        toDoubleExact(Long.MAX_VALUE) ---> error
        toDoubleExact(Long.MIN_VALUE) ---> ok
        toDoubleExact(1L << 53) ---> ok
        toDoubleExact((1L << 53) + 1) ---> error
        toDoubleExact((1L << 53) + 2) ---> ok

      JUSTIFICATION :
      Converting between a double value and a long value is made easy through casting, but it is difficult to detect when casting loses information about the original value. These new methods would make that detection less difficult.

      My want for these methods comes up most frequently in the context of JSON serialization. Suppose a Java server is communicating with a JavaScript client and JSON is the data interchange format. The Java server might send data to the client that includes long values: ids, timestamps, etc. The JavaScript client will silently coerce these values into 64-bit floating point numbers -- the language doesn't support 64-bit integers.

      In these situations, there might or might not be a client-side runtime error resulting from the coercion to a double. If the client echoes these values back to the server in some fashion ("update the name of the user with id=X") there might or might not be a server-side runtime error resulting from the coercion back to a long. If I'm really unlucky, there will be no runtime errors at all but the combined behavior will be wrong. I want to catch potential problems like this as soon as possible, close to the source, and I think to{Long,Double}Exact would help me do that.

      Double.doubleToLongBits and Double.longBitsToDouble don't quite cover the same use case.


      Attachments

        Issue Links

          Activity

            People

              bpb Brian Burkhalter
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              6 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: