Print Float Value Upto N Decimals In C Programming

Prashant | Sun, 14 Jun, 2020 | 145

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

In this tutorial we will come to kn ow how to print a float number upto N decimal places ?

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.

 

 

 

 

 

 

 

Related Articles :- 

1Introduction And Getting Started With C

2Basic Of C Language

3. Why We Should Use C Language

4. Applications Of C Programming

5. Basic Rules For Writting C Program

6. Keywords In C Language

7. Comments In C Programming

8. Tokens In C

9. Difference Between Int Main And Void Main

10. C Processor And Macros

11. Variables In C

12. Types Of Variables In C

13. Difference Between Local And Global Variable

14. Difference Bwtween Auto / Extern / Static Variable

15. Constant In C

16. How To Access Global Variable Using Extern Keyword In C

17. Exit And Return Staterment In C

18. Print Float Value Upto N Decimals In C Programming

19. How To Print Multiline Message Using Single Printf In C Programming ?

20. What Value Returned By Scanf Function In C Language ?

21. What Value Is Returned By Printf And Scanf In C

22. What Do 'Lvalue' And 'Rvalue' Mean In C/C++?

23. Errors In C Programming ?

0 comments
Leave a comment