javafloating-pointstrictfp

Strictfp returns different results on different systems


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?


Solution

  • 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: