Search code examples
c++typesdoublerounding-error

Handling doubles with large integer parts in C++


I need to handle sub-metre coordinates in C++ which have large integer parts (e.g. 515876.12 // 5117789.22), but I'm having issues with rounding:

double inUTMX = 560351.12 is displayed as 560351
double inUTMY = 5113570.22 is displayed as 5.11357e+06

I can normalise the coordinates for processing if necessary (e.g. /1e5), but I need to read-in the sub-metre coordinates via command line in the first place. Trouble is they always get rounded.

Is there a neat way to deal with doubles that have large integer values in C++?

(Tried it in Python it stores the entire precision fine as a float, just wondering where I'm going wrong.)

Any ideas / pointers much appreciated.


Solution

  • You can modify how doubles are streamed by using std::setprecision.

    Example:

    #include <iostream>
    #include <iomanip>
    
    int main () {
       double inUTMX = 560351.12;
       double inUTMY = 5113570.22;
    
       std::cout << std::setprecision(20) << inUTMX << std::endl;
       std::cout << std::setprecision(20) << inUTMY << std::endl;
    
      return 0;
    }
    

    Output:

    560351.11999999999534
    5113570.2199999997392