1

I am trying to print double and integers as double. For doing so, I wrote the following program:

int main()
{
    string object="1";
    std::stringstream objectString;
    objectString << std::setprecision(8) << atof(object.c_str());                
    cout<<"ObjectString="<<objectString.str()<< " "<<std::setprecision(10) <<  double(atof(object.c_str())) <<"\n";
}

I expected the output to be:

ObjectString=1.0  1.0

However, I am getting the output as:

ObjectString=1  1

Can someone please suggest as to where am I going wrong?

qxz
  • 3,814
  • 1
  • 14
  • 29
Alexander Fell
  • 185
  • 1
  • 11

2 Answers2

5

To force trailing zeros, use std::fixed:

std::string object = "1";
std::stringstream objectString;
objectString << std::fixed << std::setprecision(8) << atof(object.c_str());                
std::cout << "ObjectString=" << objectString.str() << " ";
std::cout << std::fixed << std::setprecision(10) << double(atof(object.c_str())) << "\n";

Output:

ObjectString=1.00000000 1.0000000000
Holt
  • 36,600
  • 7
  • 92
  • 139
qxz
  • 3,814
  • 1
  • 14
  • 29
1

The way to force the output to always show the decimal point is to use std::showpoint:

#include <iostream>
#include <iomanip>

int main() {
    double d = 1.0;
    std::cout << std::setprecision(1) << d << '\n';
    std::cout << std::setprecision(1) << std::showpoint << d << '\n';
    return 0;
}

[temp]$ ./a.out
1
1.
[temp]$ 
Pete Becker
  • 74,985
  • 8
  • 76
  • 165