Division by 1000 rounds off double var and loses the decimal places

358 views Asked by At
#include<iostream>
using namespace std;

int main()
{
    unsigned int x = 293125555;

    double y =  (double)x/1000.0;

    cout << y << endl;

    return 0;
}

I expect the output to be 293125.555 but i get 293126 instead. Is this because of the way double are stored in memory?

2

There are 2 answers

0
ne3suszr On

std::numeric_limits<T> in limits:

Provides information about the properties of arithmetic types (either integral or floating-point) in the specific platform for which the library compiles.

std::setprecision in iomanip:

Sets the decimal precision to be used to format floating-point values on output operations.

So, you can use:

#include <iostream>
#include <iomanip>  // setprecision()
#include <limits>

using namespace std;

int main()
{
    unsigned int x = 293125555;
    double y = (double)x/1000.0;

    cout << setprecision(numeric_limits<double>::digits10 + 1)
         << y
         << endl;

    return 0;
}

and get the expected result:

293125.555
8
Iman Kianrostami On

Your problem is causing by cout. You should set the precision configuration for cout before using it as describer here

[precision:] Manages the precision (i.e. how many digits are generated) of floating point output performed by std::num_put::do_put.

You should modify your code like this to get the expected result:

cout.precision(3);
cout << y << endl;