How to Use Setprecision in C++

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



Leave a reply



Submit