How to print float value till number of decimal points using printf in C language?

Learn: How to print a float value with any number of digits after the decimal point in C programming language using printf() function?
Submitted by Manju Tomar, on September 07, 2017

Given a float value and we have to print the value with specific number of decimal points.

Consider the given code, here we have a float variable named num and its value is "10.23456".

#include <stdio.h>

int main()
{
	float num = 10.23456f;
	printf("num = %f\n",num);
	return 0;
}

Output

num = 10.234560

In this output the number of digits after decimal are 6, which is default format of float value printing.

Now, we want to print 2 digits only after decimal.

Use "%.nf" format specifier

By using this format specifier we can print specific number of digits after the decimal, here "n" is the number of digits after decimal point.

Consider the program, here we will print 2 digits after the decimal point.

#include <stdio.h>

int main()
{
    float num = 10.23456f;
    printf("num = %.2f\n",num);
    return 0;
}

Output

num = 10.23

Here, we are using "%.2f" to print 2 digits after the decimal point, similarly we can print any number of digits.

I hope you will enjoy this post, if you have any query? Please leave your comment.

C Language Tutorial »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.