Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

Decimal Precision

Set Decimal Precision

You may have observed that when printing a floating-point number, the output displays numerous digits after the decimal point.

Example

float myFloatNum = 3.5;
double myDoubleNum = 19.99;

printf(“%f\n”, myFloatNum); // Outputs 3.500000
printf(“%lf”, myDoubleNum); // Outputs 19.990000 

To eliminate trailing zeros and set decimal precision when printing, you can use a dot ( . ) followed by a number indicating how many digits should appear after the decimal point.

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