Printing float values with fixed number of decimal places through cout in C++

Here, we will learn how to print float value with fixed number of decimal places using cout in C++ program?

cout prints a floating pointer number with a maximum of 6 decimal places (some compilers may print 5 decimal places) by default (without trailing zeros).

Consider the give statement

int main()
{
	float x=10.38989445f;
	cout<<x<<endl;

	return 0;
}

The output would be 10.3899

How to print float numbers with fixed number of decimal places?

We can print float numbers with fixed number of decimal places using std::fixed and std::setprecision, these are the manipulators, which are defined in the iomanip header file.

Syntax of setprecision

std::setprecision(int n)

Here, n is the number of digits after the decimal point (number of decimal places)

Read more: std::setprecision

Consider the given example

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	float x=10.3445f;
	
	cout<<fixed<<setprecision(5)<<x<<endl;
	cout<<fixed<<setprecision(2)<<x<<endl;
	cout<<fixed<<setprecision(3)<<x<<endl;
	cout<<fixed<<setprecision(0)<<x<<endl;
	
	return 0;
}

Output

10.34450
10.34 
10.344
10

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.