Hello Members,

I have a basic java question about non-terminating float values:

public class FloatandDouble
{
    public static void main(String args[]){
        float a =  1.0f/3.0f;
        System.out.println (a); 
        System.out.println (b); 
    }
}

The output of the program is 0.33333334. Why is it not 0.33333333?

Thank you

Because float values are stored in binary, just 1s and 0s, and the fractional part is made up from the values 1/2, 1/4, 1/8. 1/16, 1/32 etc
But there's no way to represent the value 1/3 exactly with any finite number of those fractions. So the last digit will always be slightly wrong. It's the same for 1/5, 1/7 etc They cannot be exactly represented in a binary floating point number.

Hello James,

Thank you for the reply!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.