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.
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).
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.
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).
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.
#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; }
#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; }
std::cout.precision(2);
std::cout<<std::fixed;
when you are using operator overloading try this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With