1

I'm using the following method on Windows 8 (Intel Atom Z3775):

public static strictfp void main(String args[])
{
    float a = 0.000000002f;
    float b = 90000300000000004f;
    float c = a * b;
    System.out.println(c);
}

which gives me: 1.80000592E8

When running

public strictfp void calculate()
{
    float a = 0.000000002f;
    float b = 90000300000000004f;
    float c = a * b;
    Toast.makeText(getApplicationContext(), c + "", Toast.LENGTH_LONG).show();
}

i get: 1.8000059E8

Why do they differ? Am I using strictfp wrong?

Geosearchef
  • 600
  • 1
  • 5
  • 22
  • What happens if you print `String.format("%08x", Float.floatToIntBits(c))` instead in both cases? – Andy Turner Apr 14 '16 at 12:25
  • They return exactly the same string. Using Float.toString(c) to convert to String on both plaforms doesn't help. – Geosearchef Apr 14 '16 at 12:33
  • Right - so the actual numbers are bitwise-identical. There is simply a difference in the implementation of the algorithm for turning the float into a string. – Andy Turner Apr 14 '16 at 12:34

2 Answers2

1

You have confirmed that printing the hex representation of the floats shows that the values are the same:

String.format("%08x", Float.floatToIntBits(c))

This means that there is a difference in the implementation of how a float is converted to a String.

Notice that the OpenJDK implementation of java.lang.Float.toString(float) invokes a method from sun.misc.FloatingDecimal - i.e. it is a JDK-specific implementation.

You'd need either:

  • To ensure that you always run the code using the same implementation
  • To provide your own implementation which always produces the same result
  • To specify a shorter format, so that the strings are the same to that many decimal places.
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Well, the displaying method certainly differs...

Adrian Roman
  • 534
  • 4
  • 8