3

The following code:

double x = 3.14;
double y = 3.14159265359;
cout<<fixed<<setprecision(6)<<x<<", "<<y<<endl;

prints: 3.140000, 3.141593

I want to print values without unnecessary zeros: 3.14, 3.141593 How to do that without using the string and stringstream classes ?

Irbis
  • 11,537
  • 6
  • 39
  • 68
  • 2
    `fixed` makes the stream to show trailing zeros. Don't use it. – Andriy Oct 21 '13 at 15:05
  • Fixed is necessary because I want to set precision for the fractional part of the number. Without fixed I get 3.14159 – Irbis Oct 21 '13 at 15:15
  • 2
    iostreams doesn't have manipulators that are sophisticated enough to do this, it really is up to you to whack those zeros from the string. – Hans Passant Oct 21 '13 at 15:35
  • possible duplicate of [Prevent scientific notation in ostream when using << with double](http://stackoverflow.com/questions/2335657/prevent-scientific-notation-in-ostream-when-using-with-double) – DogDog Oct 21 '13 at 16:09

2 Answers2

2

When neither fixed nor scientific format is chosen, the meaning of setprecision is the number of all digits to output (not just after the dot).

Therefore, this should work for you

double x = 3.14;
double y = 3.14159265359;
cout<<setprecision(7)<<x<<", "<<y<<endl;

Output:

3.14, 3.141593
Andriy
  • 8,486
  • 3
  • 27
  • 51
2

You may use cmath to count the digit of integer parts as shown:

but if number small than 0.1 will be wrong

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main(){
    double a = -123.456789;
    double b = 4567.45;
    if (a > 1 || a < -1){
        cout << setprecision(5 + int(log10(fabs(a)) + 1)) << a << endl; //anser is -123.45679
    }
    else {
        cout << setprecision(5) << a << endl;    // if a = 0.0123456 answer will be 0.012347
    }
    if (b > 1 || b < -1){
        cout << setprecision(5 + int(log10(fabs(b)) + 1)) << b << endl; //anser is 4567.45
    }
    else {
        cout << setprecision(5) << b << endl;
    }
}
藍色鬱
  • 21
  • 5