How to store the returned value of setprecision() ?
For example:-
float fl = /* assign the value returned by setprecision() */ ;
How to store the returned value of setprecision() ?
For example:-
float fl = /* assign the value returned by setprecision() */ ;
I think you're mixing up setprecision()
. Let's clear it with an example shall we?
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main () {
double f =3.14159;
std::cout << std::setprecision(5) << f << '\n';
std::cout << std::setprecision(9) << f << '\n';
std::cout << std::fixed;
std::cout << std::setprecision(5) << f << '\n';
std::cout << std::setprecision(9) << f << '\n';
return 0;
}
See the double f
? Okay so f
has a value of 3.14159
. And if we want to control how much places we need to show after the decimal place we'll use setprecision()
.
Sets 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 manipulator is declared in header .
and why do you need to use setprecision()
for assigning value to a variable?
Hopefully this will give you a clear idea of how to use setprecision()
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double var = 10.0 / 3.0 ;
cout << setprecision(10) << var;
return 0;
}
result: 3.333333333
Let's say you are accepting an input float and you set the precision of the input
std::string s;
std::cin >> std::setprecision(3) >> s;
float f = std::stof(s);
https://en.cppreference.com/w/cpp/string/basic_string/stof
You could also do something similar with other streams