×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

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

Printing float value till number of decimal points using printf() in C

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

Example

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.

Example

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.