2

I am converting an int to a double by dividing the integers by powers of 10. For integers with 7 or greater digits, it appears that rounding is performed when I cast an int into a double. Why is this happening and how can I avoid this rounding?

#include <iostream>
using namespace std;

double add_decimals(int x, int decimal_places)
{
    double ret = 1.0 * x;
    cout << "x= " << x << endl;
    cout << "ret before changes= " << ret << endl;
    for (int i = 0; i < decimal_places; ++i)
    {
        ret /= 10;
    }
    return ret;
}

int main() 
{
    double d = add_decimals(1234566, 2);
    cout << "d= " << d << endl;
}
Stack Danny
  • 7,754
  • 2
  • 26
  • 55
zzz2991
  • 717
  • 3
  • 11
  • 20

1 Answers1

1

There isn't any; you're just not observing the values correctly.

Quick fix:

std::cout << "d= " << std::fixed << d << endl;

You'll need #include <iomanip> to use std::fixed.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055