Floating-point conversion occurs when a value is converted between floating-point types, such as float, double, and long double, or between floating-point and integer types. The conversion rules determine whether the value is preserved, rounded, or truncated.
#include <stdio.h>
int main(void)
{
float f = 3.1415926535f;
double d = f;
long double ld = d;
printf("float = %.9f\n", f);
printf("double = %.9f\n", d);
printf("long double = %.9Lf\n", ld);
return 0;
}
Example Output #
The exact output depends on the implementation and floating-point representation. A common result is:
float = 3.141592741
double = 3.141592741
long double = 3.141592741
Explanation #
The first assignment stores a decimal value in a float:
float f = 3.1415926535f;
A float cannot represent every decimal fraction exactly. The value is rounded to a representable floating-point value.
The next assignment converts that stored value to double:
double d = f;
This conversion preserves the value represented by f, but it does not restore precision that was already lost when the value was stored as a float.
Similarly:
long double ld = d;
converts the double value to long double. The conversion preserves the value represented by d, subject to the rules of the implementation.
Floating-Point Conversion Rules #
| Conversion | General behavior |
|---|---|
float to double |
Value is preserved |
double to long double |
Value is preserved |
long double to double |
May lose precision or range |
double to float |
May lose precision or range |
| Integer to floating-point | Exact if representable; otherwise rounded to an adjacent representable value |
| Floating-point to integer | Fractional part is discarded toward zero |
For example:
double value = 9.75;
int number = (int)value;
The resulting integer is 9, because conversion from floating-point to integer discards the fractional part.
If the integral part of a floating-point value cannot be represented by the destination integer type, the conversion has undefined behavior in C.