How can I use fixed setprecision(2) only ONCE? Or at least restore to default behaviour?
You can save the previous flags and precision, and then restore them afterwards, eg:
// Detect if train has cargo:
if (cargo_unit)
{
// If cargo exists, print output:
std::ios_base::fmtflags old_flags = cout.flags();
std::streamsize old_prec = cout.precision();
std::cout << std::fixed << std::setprecision(2);
/* alternatively:
std::ios_base::fmtflags old_flags = cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::streamsize old_prec = cout.precision(2);
*/
std::cout << " Cargo: " << cargo_unit->getDesc() <<
std::endl << " Weight: " << cargo_unit->getWeight() << std::endl;
cout.precision(old_prec);
cout.flags(old_flags);
}
How to set precision of a float
You can't do that, since precision is determined by the data type (i.e. float
or double
or long double
). If you want to round it for printing purposes, you can use the proper format specifiers in printf()
, i.e. printf("%0.3f\n", 0.666666666)
.
Equivalent of C++ std::setprecision(20) using printf in C
You can use the "%.20g" specifier. g is IMHO usually better than f since it doesn't print trailing zeros, and handles large/small values sensibly (changing to e format).
Also note that with the "g" specifier, the precision (the "20" in this case) specifies the number of significant digits rather than the number of digits after the decimal point.
C++ std::setprecision in C#
It sounds like you just want to print the number with a specific number of significant digits. You can simply use the G format string to specify the number of digits to use.
output.Write("{0:G10}", value);
Related Topics
Sharing a Global/Static Variable Between a Process and Dll
How to Convert a Reverse Iterator to a Forward Iterator
C++ Sort Keeping Track of Indices
😃 (And Other Unicode Characters) in Identifiers Not Allowed by G++
Cancelling a Thread Using Pthread_Cancel:Good Practice or Bad
Scope of Exception Object in C++
Detecting Constexpr with Sfinae
Value Initialization and Non Pod Types
Mixing Debug and Release Library/Binary - Bad Practice
Properly Print Utf8 Characters in Windows Console
Error: Expected Class-Name Before '{' Token
How to Use Setprecision in C++
How to Compose Output Streams, So Output Goes Multiple Places at Once
Createfile: Direct Write Operation to Raw Disk "Access Is Denied" - Vista, Win7
Why Does "Extern Const Int N;" Not Work as Expected
Explicit Specialization in Non-Namespace Scope Does Not Compile in Gcc