3

Consider the following code:

System.out.printf("%f%n", 123456796f);

This prints 123456800 on my system, so the value was rounded up by 4. Is rounding up mandated in this situation, or could the compiler have decided to round down by 4 just as well, yielding 123456792?

0

1 Answer 1

3

Java Language Specification, §3.10.2, Floating-Point Literals:

The details of proper input conversion from a Unicode string representation of a floating-point number to the internal IEEE 754 binary floating-point representation are described for the methods valueOf of class Float and class Double of the package java.lang.

Float.valueOf Javadoc:

s is regarded as representing an exact decimal value in the usual "computerized scientific notation" or as an exact hexadecimal value; this exact numerical value is then conceptually converted to an "infinitely precise" binary value that is then rounded to type float by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic [...]

2
  • In addition, §4.2.4 (docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.4) mandates that other floating-point operations have the same rounding mode, so valueOf() is consistent with the rest of Java. Nov 10, 2014 at 15:00
  • It may be worth noting that the above language would require that 123456788.000000000000 (with any number of zeroes) must be rounded down to 123456784, but 123456788.000000000001 (with any number of zeroes before the first non-zero digit) must be rounded up to 123456792. Rather than actually evaluate the latter number to arbitrary precision, a good float parser will typically identify cases where any non-zero digit will force a value to round up, and then simply toss out zeroes until it sees a non-zero digit or the end of the numeric representation.
    – supercat
    Nov 12, 2014 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.