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




Comments and Discussions!

Load comments ↻






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