Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use setprecision in C++

Tags:

c++

I am new in C++ , i just want to output my point number up to 2 digits. just like if number is 3.444, then the output should be 3.44 or if number is 99999.4234 then output should be 99999.42, How can i do that. the value is dynamic. Here is my code.

#include <iomanip.h>
#include <iomanip>
int main()
{
    double num1 = 3.12345678;
    cout << fixed << showpoint;
    cout << setprecision(2);
    cout << num1 << endl;
}

but its giving me an error, undefined fixed symbol.

like image 493
Malik Avatar asked Mar 19 '14 18:03

Malik


People also ask

How do you use Setprecision?

To set the precision in a floating-point, simply provide the number of significant figures (say n) required to the setprecision() function as an argument. The function will format the original value to the same number of significant figures (n in this case).

What is Setprecision function?

The setprecision() function is a built-in function that comes with the iomanip library. As the name suggests, it helps us to set the precision (significant figures/decimal​ places) of an output.

What is std :: Setprecision () in C++?

std::setprecisionSets the decimal precision to be used to format floating-point values on output operations. Behaves as if member precision were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).

What is decimal in C?

This information refers to fixed-point decimal data types as decimal data types. The decimal data type is an extension of the ANSI C language definition. When using the decimal data types, you must include the decimal. h header file in your source code.


3 Answers

#include <iomanip> #include <iostream>  int main() {     double num1 = 3.12345678;     std::cout << std::fixed << std::showpoint;     std::cout << std::setprecision(2);     std::cout << num1 << std::endl;     return 0; } 
like image 88
piokuc Avatar answered Oct 01 '22 17:10

piokuc


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

You can enter the line using namespace std; for your convenience. Otherwise, you'll have to explicitly add std:: every time you wish to use cout, fixed, showpoint, setprecision(2) and endl

int main() {     double num1 = 3.12345678;     cout << fixed << showpoint;     cout << setprecision(2);     cout << num1 << endl; return 0; } 
like image 39
Loyce Avatar answered Oct 01 '22 17:10

Loyce


std::cout.precision(2);
std::cout<<std::fixed;

when you are using operator overloading try this.

like image 25
ANSHUMAN KARMAKAR Avatar answered Oct 01 '22 18:10

ANSHUMAN KARMAKAR