3
float f1 = 123.125;
int i1 = -150;

f1 = i1;    // integer to floating conversion
printf("%i assigned to an float produces %f\n", i1, f1);

Output:

-150 assigned to an float produces -150.000000

My question is why the result has 6 zeros (000000) after the . and not 7 or 8 or some number?

4 Answers 4

7

That's just what printf does. See the man page where it says

f, F

The double argument shall be converted to decimal notation in the style "[-]ddd.ddd", where the number of digits after the radix character is equal to the precision specification. If the precision is missing, it shall be taken as 6; if the precision is explicitly zero and no '#' flag is present, no radix character shall appear. If a radix character appears, at least one digit appears before it. The low-order digit shall be rounded in an implementation-defined manner.

(emphasis mine)

It has nothing to do with how 150 is represented as a floating point number in memory (and in fact, it's promoted to a double because printf is varargs).

Sign up to request clarification or add additional context in comments.

Comments

3

The number of zeros you see is a result of the default precision used by the %f printf conversion. It's basically unrelated to the integer to floating point conversion.

Comments

3

Because the C standard (§7.19.6.1) says that in the absence of information to the contrary, %f will print 6 decimal places.

f,F A double argument representing a floating-point number is converted to decimal notation in the style [−]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is zero and the # flag is not specified, no decimal-point character appears.

Comments

2

Floating point arithmetic is not exact. printf is just showing that number of zeroes.

From the documentation:

The default number of digits after the decimal point is six, but this can be changed with a precision field. If a decimal point appears, at least one digit appears before it. The "double" value is rounded to the correct number of decimal places.

2 Comments

Why it appended 6 zeros. Not 7 or 8 zeros. The number of zeros based on my hardware?
@Nano HE: because the standard says "[i]f the precision is missing, it is taken as 6; ..."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.