Floating point format for std::ostream
std::cout << std::fixed << std::setw(11) << std::setprecision(6) << my_double;
You need to add
#include <iomanip>
You need stream manipulators
You may "fill" the empty places with whatever char you want. Like this:
std::cout << std::fixed << std::setw(11) << std::setprecision(6)
<< std::setfill('0') << my_double;
Configuring std::ofstream format for floating point numbers
One way to do this is with some string manipulation. Format to a stringstream using scientific notation, then split the string on the 'e'. Now you have the parts you can format yourself.
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
std::string format(double val)
{
std::ostringstream oss;
oss << std::scientific << std::setprecision(14) << val;
auto result = oss.str();
auto match = result.find('e');
if (match == std::string::npos)
{
// Should never get here -- maybe throw
}
oss.str("");
auto exp = std::stoi(result.substr(match+1));
oss << result.substr(0, match) << 'E'
<< std::setw(5) << std::setfill('0')
<< std::internal << std::showpos << exp;
result = oss.str();
return result;
}
int main()
{
std::cout << format(3.99147034531211e-3) << '\n';
std::cout << format(6.02214085774e23) << '\n';
}
Output:
3.99147034531211E-0003
6.02214085774000E+0023
std::ofstream set precision for Floating point format
You have to use std::fixed
and std::setprecision
:
ofs << "Elapsed time= " << std::fixed << std::setprecision(6)
<< elapsed << "(s)"
<< std::endl;
Further difftime()
returns a double not a float.
double difftime(time_t time1, time_t time0);
The
difftime()
function returns the number of seconds elapsed between time time1 and time time0, represented as a double.
Global formatting options for floating point numbers
Overloading streams is a bad idea, but you can wrap them. If you want to do a special but common pre/post-processing, define a custom (templated) class that has a stream as member (maybe affected in constructor), and delegates actual io to that stream after preprocessing input and/or do some post-processing after.
class Printer {
ostream &ost;
Printer(ostream& st): ost(st) {
// other initializations ...
}
Printer& operator << (double d) {
ost << std::scientific << std::showpos << std::setprecision(15) << std::to_string(s);
return *this;
}
// others: ostream conversion, other processing...
}
Prevent scientific notation in ostream when using with double
To set formatting of floating variables you can use a combination of setprecision(n)
, showpoint
and fixed
. In order to use parameterized stream manipulators like setprecision(n)
you will have to include the iomanip library:
#include <iomanip>
setprecision(n)
: will constrain the floating-output to n
places, and once you set it, it is set until you explicitly unset it for the remainder of the stream output.
fixed
: will enforce that all floating-point numbers are output the same way. So if your precision is set to 4 places, 6.2
, and 6.20
will both be output as:
6.2000
6.2000
showpoint
: will force the decimal portions of a floating-point variable to be displayed, even if it is not explicitly set. For instance, 4
will be output as:
4.0
Using them all together:
outfile << fixed << showpoint;
outfile << setprecision(4);
outfile << x;
C++ How do I format a float with std::string?
Found a way using stringstream :) Then it uses the default ostream float format and pushes it to a string :)
std::stringstream ss;
std::string s;
ss << 3.4;
ss >> s;
std::cout << s.append("f") << std::endl;
generates the following output:
3.4f
Limiting a floating point ostream print to a certain length?
My temporary solution is width(7)
and precision(4)
. It gives me 4 digits after the decimal point and 3 which is space to put the minus sign, a single digit, and the decimal point. I have to check and modify width in order to accomodate (some of the) values larger than 99.9999
or less than -9.9999
to preserve alignment. This has the benefit that 567890123
will not be printed as 5678901
, all it will do is throw off alignment (a lot, it will be printed as 567890123.0000
).
What are the default Format Flags (and widths) for double output in a std::stringstream?
The defaults are setup by std::basic_ios::init
and are the same for all streams derived from ios_base
. The defaults are:
rdbuf() sb
tie() 0
rdstate() goodbit if sb is not a null pointer, otherwise badbit.
exceptions() goodbit
flags() skipws | dec
width() 0
precision() 6
fill() widen(’ ’)
getloc() a copy of the value returned by locale()
iarray a null pointer
parray a null pointer
So the default precision is 6
Setting minimum number of decimal places for std::ostream precision
I do not think there is a way to achieve what you are asking without turning the number into a string (with high precision), and stripping off the trailing zeros.
This is appropriate, because just because there are trailing zeros doesn't mean there isn't precision there, and the run-time can't tell that.
For example, if I measure the weight of an object with a cheap scale, it may be 1.0 kgs.
If I weigh it with a high-accuracy scale, it may be 1.00000 kgs. Just because there are trailing zeros, doesn't mean that accuracy should be discarded.
Related Topics
How to an Share Address Mapping Between Two Unrelated Processes on Linux
Why Is Padding Added for Multiple Data Members of Structures and Not for Single Members
Is C/C++ Bool Type Always Guaranteed to Be 0 or 1 When Typecast'Ed to Int
Which C++ Standard Library Wrapper Functions Do You Use
What Is the Default Constructor for C++ Pointer
How to Convert Euler Angles to Directional Vector
Why Can't I Add a Qgridlayout to a Qmainwindow
Find Argc and Argv from a Library
While (1) VS. for (;;) Is There a Speed Difference
Iterate Through Struct and Class Members