Reputation: 1464
Below is some simple code I am working with:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float f = 1.66f;
int d = (int)f;
double g = (double)d;
cout.precision(6);
cout<<g<<"\n";
}
I want it to print 1.000000
but it prints only 1
. But, even after upgradation of int to double, doesn't it automatically convert it to an integer value?
Upvotes: 2
Views: 2221
Reputation: 353
Setprecision sets how precise the result has to, e.g.
std::cout << (1.f)/6 << std::endl; // prints 0.166667
std::cout.precision(7);
std::cout << (1.f)/6 << std::endl; // prints 0.1666667
But it does not require that 0's are printed out, consider:
std::cout.precision(5);
std::cout << 1.1110f << std::endl; // prints 1.111
std::cout << 1.1111f << std::endl; // prints 1.1111
And as coincoin suggests the solution to get 0's printed out is to use std::fixed!
Upvotes: 1
Reputation: 4685
You can add cout << std::fixed;
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float f = 1.66f;
int d = (int)f;
double g = (double)d;
cout.precision(6);
cout << std::fixed;
cout<<g<<"\n";
}
and you get 1.000000
Explanations (edit)
When you use std::fixed :
When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.
When you use the std::defaultfloat (the one you are using) :
When floatfield is set to defaultfloat, floating-point values are written using the default notation: the representation uses as many meaningful digits as needed up to the stream's decimal precision (precision), counting both the digits before and after the decimal point (if any).
That's why the following .000000
are considered irrevelant !
(If you had 1.00001
it would have been printed)
Upvotes: 7