What is the most elegant way to output a floating point number in C++ with no scientific notation or trailing zeros?
float a = 0.000001f;
float b = 0.1f;
cout << "a: " << a << endl; // 1e-006 terrible, don't want sci notation.
cout << "b: " << b << endl; // 0.1 ok.
cout << fixed << setprecision(6);
cout << "a: " << a << endl; // 0.000001 ok.
cout << "b: " << b << endl; // 0.100000 terrible, don't want trailing zeros.
You need to write: std::cout << fixed; std::cout << setprecision(2) << f; fixed disables the scientific notation i.e. 1.23e+006 and fixed is a sticky manipulator so you need to disable it if you want to revert back to scientific notation.
you can round-off the value to 2 digits after decimal, x = floor((x * 100) + 0.5)/100; and then print using printf to truncate any trailing zeros..
The C++ double should have a floating-point precision of up to 15 digits as it contains a precision that is twice the precision of the float data type. When you declare a variable as double, you should initialize it with a decimal value. For example, 3.0 is a decimal number.
I am not sure about the "most elegant way" but here's one way.
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std ;
string fix( float x, int p )
{
ostringstream strout ;
strout << fixed << setprecision(p) << x ;
string str = strout.str() ;
size_t end = str.find_last_not_of( '0' ) + 1 ;
return str.erase( end ) ;
}
int main()
{
float a = 0.000001f ;
float b = 0.1f ;
cout << "a: " << fix( a, 6 ) << endl; // 0.000001 ok.
cout << "b: " << fix( b, 6 ) << endl; // 0.1 ok.
return 0;
}
You could perhaps create your own I/O manipulator if you need to to a lot of this kind of output. That is arguably more elegant, but the implementation could be similar.
If string manipulating doesn't hurt your eyes:
std::string fixedfloat(float x)
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(std::cout.precision()) << x;
std::string str = ss.str();
return str.substr(0, str.find_last_not_of('0') + 1);
}
int main()
{
float b = 0.1f;
std::cout << std::setprecision(6) << fixedfloat(b);
}
or
class fixedfloat
{
public:
fixedfloat(float x) : x(x) {}
float value() const { return x; }
private:
float x;
};
ostream &operator<<(ostream &out, const fixedfloat &f)
{
ostringstream ss;
ss << fixed << setprecision(out.precision()) << f.value();
string str = ss.str();
out << str.substr(0, str.find_last_not_of('0') + 1);
return out;
}
int main()
{
float b = 0.1f;
cout << setprecision(6) << fixedfloat(b);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With