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?

fredoverflow
  • 256,549
  • 94
  • 388
  • 662

1 Answers1

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 [...]

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • In addition, §4.2.4 (https://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. – Philipp Wendler Nov 10 '14 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 '14 at 19:28