Understanding Decimal Precision in C: Controlling Floating Point Output
Discover how to set decimal precision when printing floating point numbers in C. Learn to control the number of digits displayed after the decimal point, ensuring your output is clear and formatted according to your requirements.
C Decimal Precision
Set Decimal Precision
When you print a floating point number in C, you may notice that the output displays many digits after the decimal point. For example:
Example
float myFloatNum = 3.5;
double myDoubleNum = 19.99;
printf("%f\n", myFloatNum); // Outputs 3.500000
printf("%lf", myDoubleNum); // Outputs 19.990000
Controlling Decimal Precision
If you want to remove the extra zeros and control how many digits are displayed after the decimal point, you can use a dot (.) followed by a number to specify the desired precision:
Example
float myFloatNum = 3.5;
printf("%f\n", myFloatNum); // Default will show 6 digits after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
Output Examples
Output
3.500000
3.5
3.50
3.5000
This allows you to control how many decimal places you want to display when printing floating point numbers.