0

I have a problem with showing a float number with exactly 8 decimals. I use setprecision but the problem is that for example i want to print 1.61666666 and with setprecision it shows 1.61666667. I don't want to round it, just to print the first 8 decimals.

cout.precision(8);
cout << fixed << 97.0/60.0 << endl;
printf("%.8f", 97.0 / 60.);

this is the code

nel_3001
  • 11
  • 2

2 Answers2

0

You can always use stringstream tomfoolery:

string foo{static_cast<std::ostringstream&>(std::ostringstream() << setprecision(10) << 97.0 / 60.0).str()};
foo.resize(foo.size() - 1);

Incidentally you might consider using ratio here if you're just looking for a constant of sorts.

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • @nel_3001 Old versions of gcc had a bug when moving/copying `stringstreams` maybe that's what you're seeing? http://ideone.com/ENbkGm – Jonathan Mee Dec 06 '14 at 14:51
0

Well, if you must (although I don't understand why you would want the 'wrong' number)

#include <iomanip>
#include <iostream>
#include <sstream>

using namespace std;

void concat_print(double val, int precision)
{
    stringstream stream;
    stream << setprecision(precision + 1) << val;
    // for (auto i = 0; i < stream.str().size() - 1; ++i)  <- C++11 only
    for (size_t i = 0; i < stream.str().size() - 1; ++i)
        cout << stream.str()[i];
}

int main()
{
    // double number { 1.616666666666 };
    double number = 1.616666666666;
    cout << "With normal setprecision: " << setprecision(8)
         << number << '\n';
    cout << "With ugly hack: ";
    concat_print(number, 8);
}
smoothware
  • 898
  • 7
  • 19
  • prog.cpp:18: error: ISO C++ forbids declaration of 'i' with no type – nel_3001 Dec 06 '14 at 15:04
  • 1
    It is not my problem, if you are not able to enable C++11 features. So please stop giving some meaningless Error, implying that the code sucks and one better give you a good reason why it doesn't compile with your toolchain. Also giving line numbers is pretty pointless, if you dont use the exact code. I will edit it to help you resolve this error. Also please note, that my solution is rather bad and you should combine it with the solution of another answer, saving the for loop completely – smoothware Dec 06 '14 at 15:29