Reputation: 11
The number must be displayed with exactly five digits after the decimal. If the number is 0 to display only 0 instead of 0.00000. If the number has zeros in his decimal recording only show numbers other than zero, for example 0.08500 instead of outputting 0.085 //s0 is my variable
if (s0==) cout<<"0"
else cout<<setiosflags(ios::fixed)<<setprecision(5)<<s0;
Upvotes: 0
Views: 2706
Reputation: 356
std::cout << std::setprecision(5) << s0; This is the best method for setting precision.
Upvotes: 0
Reputation: 6404
You can't easily do it in C++ with the streams and << operator, because 0 is a special case.
Write a function
std::string tonice(double x)
{
char buff[64];
if(x == 0)
sprintf(Buff, "0");
else
sprintf(buff, "%5.3f", x);
return std;string(buff);
}
Then
cout << "The data is " << tonice(x) << " other bits and bats";
Upvotes: 0
Reputation: 27
It seems obvious, but could you use printf?
#include <stdio.h>
int main(){
printf("%5.3f", 0.8500000000);
return 0;
}
Upvotes: 0
Reputation: 1184
Try:
std::cout << std::setprecision(5) << s0;
In your version setiosflags(ios::fixed)
is forcing trailing zeros.
Upvotes: 2