0

How do I get std::cout to round a very small double value to zero, instead of printing values like:

6.94532807444049e-310

or

6.95321306220521e-310

I've noticed many of these overly long scientific notations that may as well be zero seem to have e-310

2 Answers2

0

There are multiple ways to round a number. If you wanted to the nearest whole you should just use int.

Another way is using header #include iomanip and using the 'setprecision(2)' to set the width.

0

The insert operation for inserting a floating-point value into a stream produces a small result because the inserted value is small. It is the job of a formatting operation to show the value, not to make decisions about what changes you want to it, such as changing a small value to zero.

If you want small values to result in zero, you can:

  • adjust the value before inserting it into the stream, or
  • request different formatting for the value.

If you want to adjust the value by converting values below some threshold to zero, you can use code such as:

if (abs(x) < 1e-100) x = 100;

To change the formatting, one option is to use the fixed format optionally with a precision set using setprecision from <iomanip>:

std::cout << std::fixed << std::setprecision(8);

The latter may not offer the flexibility you want, if you want to show small numbers using scientific notation (say 10−20) but not very small numbers (say 10−200). There are no formatting options to allow the use of scientific notation but to chop off small numbers below an arbitrary threshold. For that, you must use the first option of changing the value yourself.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312