Setting precision on std::cout in entire file scope - C++ iomanip - c++

I'm doing some calculations, and the results are being save in a file. I have to output very precise results, near the precision of the double variable, and I'm using the iomanip setprecision(int) for that. The problem is that I have to put the setprecision everywhere in the output, like that:
func1() {
cout<<setprecision(12)<<value;
cout<<setprecision(10)<<value2;
}
func2() {
cout<<setprecision(17)<<value4;
cout<<setprecision(3)<<value42;
}
And that is very cumbersome. Is there a way to set more generally the cout fixed modifier?
Thanks

Are you looking for cout.precision ?

In C++20 you'll be able to use std::format which gives you shortest decimal representation by default, so you won't loose precision even if you don't specify it manually. For example:
std::cout << std::format("{}", M_PI);
prints
3.141592653589793
If you need a fixed precision you can store it in a variable and reuse in multiple places:
int precision = 10;
std::cout << std::format("{:.{}}", value, precision);

Related

C++ Convert string to float

I am trying to convert a string based number to float. Unfortunately I am getting either the rounded off value or truncated value. How can I fix this.
std::string text = "199102.92";
float v = std::stof(text);
std::cout<<v<<std::endl;
This results in 199103
Even if I use setprecision and fixed then it only affects the output stream but the value passed into the float variable remains 199103. How can i resort this problem.
I have also used stringstream in c++ but results seem to be the same except it just displays off well.
I need to preserve the decimal upto 2 places.
I have used stof,stod, they all do the same thing.
You may assume that I am working with currencies.
I assume that you use std::setprecision and std::fixed incorrectly.
Following works for me:
#include <iostream>
#include <iomanip>
#include <string>
string text = "199102.92";
float v = std::stof(text);
std::cout << std::setprecision(2) << std::fixed << v << std::endl;
The result is 199102.92
Compiler info: g++ 5.4.0, --std=c++11.

Can you set the qDebug() floating point precision and number format globally?

I want to use qDebug(), qInfo() and so on with a custom default floating point precision and number format.
Is there a way to define this globally?
Imagine this:
double num = 1.2;
qDebug() << "My floating point Number is: " << QString::number(num, 'f', 2);
//Output: My floating point Number is 1.20
Now I would like to avoid QString::number(num, 'f', 2) everytime I write a number and would much rather like to use a standard percision and format.
Formatting of a QDebug stream can be controlled through QTextStream manipulators. Therefore, you must call
qDebug() << fixed << qSetRealNumberPrecision(2);
in the beginning of your program.
Note, however, that the formatting state of qDebug() may change later if some (not so carefully written) code sets required formatting and doesn't restore it to the previous state after completing its job.
EDIT
It turns out that the effect of QTextStream manipulators (at least in combination with qDebug()) is limited to the containing statement and doesn't persist. So, the best you can do is define your replacement of qDebug() as follows:
#define myqDebug() qDebug() << fixed << qSetRealNumberPrecision(2)
and use it instead of qDebug():
double num = 1.2;
myqDebug() << "My floating point Number is: " << num << endl;
Output:
My floating point Number is: 1.20
You can't.
qDebug(), qFatal(), etc... return instances of the class QDebug.
The issue is that the operator QDebug::operator<<(float f) is a non virtual class member function.
You cannot define another without getting the compile error message
operator<< is ambiguous

G++ floating point precision

I have these lines in a C++ program,
auto f = log (FLT_MAX / 4);
printf("%e", f);
cout << f;
The printf result is 8.733654e+1, but cout gives me 87.3365. I checked the 32-bit hex values, they're respectively 0x3f5f94e0 and 0x3f5f94d9, meaning, there seems to be enough precision to represent the value exactly.
Do you know why cout is truncating that floating point value?
Do you know why cout is truncating that floating point value?
Because the default precision C++ streams are set to is 6.
You can change the precision with std::setprecision.
This has nothing to do with g++.
What you should do is this:
#include <limits>
#include <iomanip>
std::cout << std::setprecision(std::numeric_limits<double>::digits10+1) << f;
You can also use long double instead of double to get the maximum precision available.
Documentation
std::setprecision
std::numeric_limits

C++: write a double approximation in ofstream file, like printf("%f....)

I have this problem. I get the result from the function double sin(double x)of the library cmath. I want to write this result in a file declared as ofstream fileand I want that when the result is close to zero, write 0.000000 and not 1.22465e-16.
For example, I tried:
`double x=sin(interval*c);
file<<"value:"<<x;
printf("value:%f",x);`
where the multiplication between intervaland c is about π.
But in the file is written1.22465e-16, while in the shell is written 0.000000. How can i do to get the approximation0.000000 in ofstream file? Thanks all
If you want the same format the "%f" specifier uses (rather than the default which is "%g"), you'd use
std::cout << std::fixed;
To restore the original format, i.e., get back to using the same format as "%g" you'd use
std::cout << std::defaultfloat; // C++11
std::cout.setf(std::ios_base::fmtflags(), std::ios_base::floatfield); // pre C++11
You can check if it is below a threshold and just set it to 0
if(fabs(x) < 1e-8) x = 0;

Issue when "fixed" stream manipulator is removed

I am new to C++, learning it by my self, and I am using the book "C++ how to program - 7th edition" from Deitel. Now, please have a look at the following code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double principle = 1000;
double amount;
double rate = 0.05;
cout << "Year" << setw(21) << "Amount on deposit" << endl;
cout << fixed << setprecision(2);
for(int years=1; years<=10; years++)
{
amount = principle * pow(1.0+rate,1.0);
cout << setw(4) << years << setw(21) << amount << endl;
}
}
When I removed the "fixed" stream manipulator, the output becomes stupid, which means, just ascii letters and numbers. When I insert it, the output comes without any problem. My question is, why is this happening? Is "fixed" mandatory for all the programs which has "double" type outputs? Please help.
And another thing. What are stream manipulators? As a Java developer, I thought these might be some kind of constant variables, but it is not! They are methods? Then why the brackets are not there? Please answer to this question too.
Thanks
The output does not "become stupid": you simply let your output stream choose the format for your floating-point numbers, and it picks scientific notation. This gives you 1e+03 (which means 1*10^3) instead of 1050.00. The use of fixed tells the stream that you do not want scientific notation; you could also use scientific to force the scientific format. Since the precise format depends depends on your application requirements, the choice to use fixed or scientific is ultimately up to you.
Manipulators like fixed are functions, but if you wanted the common () for it then it would look like this:
fixed(cout); //Instead of using the << or >> you pass the stream into the manipulator function.
See this reference for more on manipulators:
http://www.cplusplus.com/reference/iostream/manipulators/
Also, fixed documentation can be found here:
http://www.cplusplus.com/reference/iostream/manipulators/fixed/
Hope this helps
It's not just ascii letter and numbers
1e+03 is scientific writing for 1*10^3 which is 1000
for reference:
http://www.cplusplus.com/reference/iostream/manipulators/fixed/
If you had chose a wider precision, your output would have been different without fixed.
cout << setprecision(6); // 6 instead of 2
Then your output would have looked more like you expected. (Incidentally, you should compute the compound interest by folding the interest earned back into the principle.)
Otherwise, with only setprecision(2), the formatter decides to use scientific notation in order to only display 2 digits of precision.
But, since you want the output to provide a fixed number of digits, what you have provided (both fixed and setprecision(2)) will do that.