pkumar
pkumar

Reputation: 4801

float and int value subtraction in Java

I think following is related to precision of float values somehow, but I'm not sure how and why exactly following behavior is observed. I have following piece of code in java:

class float_int
{
    void float_to_int(float val)
    {
        int int_val = (int)val;
        float remain_val = val - (float)int_val;
        System.out.println("val - " + val);
        System.out.println("int_val - " + (float)int_val);
        System.out.println("remain_val - " + remain_val);
    }

    public static void main(String args[])
    {
        float_int obj = new float_int();
        obj.float_to_int((float)12.345);
    }
}

I get the following output:

val - 12.345
int_val - 12.0
remain_val - 0.34500027

Now I'm not sure why I'm getting an extra "27" at the end for remain_val.

Upvotes: 0

Views: 8671

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

Because neither 12.345 nor 0.345 is exactly representable in binary floating-point.

For example:

float f = 12.345f;
System.out.printf("%.15f\n", f);  // Displays 12.345000267028809

In the above code, 12.345000267028809 is the nearest value that is exactly representable.

Upvotes: 3

Michael
Michael

Reputation: 3332

You're correct, it is because floats are not precise.

If you want your float to be represented correctly, you can use the same approach that this guy seemed to take: http://floating-point-gui.de/languages/java/

Which is to round the float:

String.format("%.2f", 1.2399) // returns "1.24"
String.format("%.3f", 1.2399) // returns "1.240"
String.format("%.2f", 1.2) // returns "1.20"

Upvotes: 2

Related Questions