Some Stranger
Some Stranger

Reputation: 73

How to prevent rounding error in c++?

How I can prevent rounding error in C++ or fix it?

Example:

float SomeNumber = 999.9999;
cout << SomeNumber << endl;

It prints out 1000!

Upvotes: 5

Views: 10262

Answers (4)

The Forest And The Trees
The Forest And The Trees

Reputation: 1856

To prevent your output being rounded, use setprecision in iomanip.

float SomeNumber = 999.9999;
std::cout << SomeNumber << std::endl; //outputs 1000
std::cout << std::setprecision (7) << SomeNumber << std::endl; //outputs 999.9999
return 0;

The actual value stored in SomeNumber will always be 999.9999 though, so you don't need to worry about the value itself (unless you need more precision than float provides).

Upvotes: 1

Lewis Diamond
Lewis Diamond

Reputation: 24911

As mentioned previously, if you're looking only for cout rounding fix, use the .precision function. If you're referring to the incapacity of floating points to represent every possible fractions, read below:

You can't avoid such rounding errors using floating point numbers. You need to represent your data in a different way. For example, if you want 5 digits of precision, just store it as a long which represent the number of your smallest units.

I.e. 5.23524 w/ precision at 0.00001 can be represented in a long (or int if your range of values fit) as 523524. You know the units are 0.00001 so you can easily make it work.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254431

By default, formatted output via std::ostream rounds floating-point values to six significant decimal figures. You need seven to avoid your number being rounded to 1000:

cout << setprecision(7) << SomeNumber << endl;
        ^^^^^^^^^^^^^^^

Also, be aware that you're close to the limit of the precision of float, assuming the commonly-used 32-bit IEEE representation. If you need more than seven significant figures then you'll need to switch to double. For example, the following prints 1000, no matter how much precision you specify:

float SomeNumber = 999.99999; // 8 significant figures
cout << setprecision(10) << SomeNumber << endl;

Upvotes: 3

cyon
cyon

Reputation: 9538

You can alter the rounding done by cout by setting the precision.

cout.precision(7);
float SomeNumber  = 999.9999;
cout << SomeNumber  << endl;

Alternatively, you can use printf from cstdio.

Upvotes: 5

Related Questions