floats

Hi,

I’ve been looking at the my class file in Jshrink, and I notice that float values like 0.03f get extracted to something like 0.029999999329447746. Clearly, this will take up bytes?
Is there a way to “trick” Java not to do that? I’ve tried to use (float)0.03 (double that is) but Java outsmarts me and makes it a float.

But why does it do this to floats anyway? Doesn’t do it to double :\

you could try strictfp, though i don’t know why you’re having this problem in the first place.

consider this test:


public class Test {
	public static void main(String args[]) {
		float x = 0.03f;
		System.out.println(x);
		x = new Float(0.03f).floatValue();
		System.out.println(x);
		x = Float.parseFloat("0.03");
		System.out.println(x);
	}
}

output:

Clearly, this will take up bytes?

As much space as a float or double takes. What you see there is the string representation.

edit:
float f1=0.3f;
float f2=(float)0.3;
double d1=0.333;

becomes:
float f = 0.3F;
float f1 = 0.3F;
double d = 0.33300000000000002D;

Yeah, it will take as much space as floating point numbers use for their representation(IEEE 754 standard)…

I know that float is 32bit, so they take up 4 bytes. But that’s in memory! What about in class files?

woogley, I tried that Test… and then I opened the class file in JShrink and this is what I see…:

  static public void main(String[] args) {
    float x;
    x = 0.029999999329447746;
    out.println(x);
    x = new Float(0.029999999329447746).floatValue();
    out.println(x);
    x = Float.parseFloat("0.03");
    out.println(x);
  }

whatever is converting that class (is it your code? or one of the optimizers?) needs to be using strictfp i think. I open it with JAD and the 0.03f remains in the classfile.

[quote]I know that float is 32bit, so they take up 4 bytes. But that’s in memory! What about in class files?
[/quote]
0.03f --> 5 characters = 5 bytes

.0.029999999329447746 --> 4 bytes

I’m not seeing a problem here…

Thanks! :slight_smile: