.f float suffix question

I'm trying to get my head around this piece of code, which demonstrates the use of integer literal suffix:

1
2
3
4
5
6
7
8
9
10
11
12
13
	{ // Demonstrating .f
		float a = 3.2;
		if ( a == 3.2 )
			std::cout << "a is equal to 3.2" << std::endl;
		else
			std::cout << "a is not equal to 3.2" << std::endl;

		float b = 3.2f;
		if ( b == 3.2f )
			std::cout << "b is equal to 3.2f" << std::endl;
		else
			std::cout << "b is not equal to 3.2f" << std::endl;
	}


The first if statement is false, whereas the second if statement where .f is used is true.

How is that possible? If a was an int, I understand that the decimal place would be lost, and a would equal 3. But a float can hold decimal values, and is equal to 3.2...no?
a float variable holds less decimal places than a double variable. The number "3.2" cannot be represented exactly in binary to a computer, similar to how 1/7 can't be represented exactly in base-10.

3.2 is initially a double. 3.2f is initially a float.
float a= 3.2; casts down from a double to a float when assigned, so you lose precision.

3.2f might be represented as something like:
11.001100110011002
3.2 (a double) might be represented as:
11.001100110011001100110011001100112

*Note I didn't actually count the number of decimal places, just note that double usually has about double of float.

These numbers are not exactly equal, so the check is false.
Last edited on
Thanks Ganado.

I wasn't relating it to binary, makes much more sense now.

I still find it tricky to know exactly when to use .f, I presume it's pretty much only when you are using relational operators with floats.
Topic archived. No new replies allowed.