- C / C++ Tip of the Day
- 07 Aug 2009 06:16:16 pm
- Last edited by KermMartian on 05 Mar 2010 01:52:20 pm; edited 2 times in total
August 7, 2009
C++ Stream Precision
Say that you're writing a program that converts GPS NMEA strings into decimal coordinates. The output of your GPS receiver, grabbed by a serial-port input program, might look something like this:
Code:
Of course, this is not particularly useful, so we will use strtok and some loop magic to create two variables, lat and lon. Here's how they'll be defined:
Code:
You'd expect that lat and long would contain 40.437187 and 73.593728 respectively, and you'd be correct. However, imagine your consternation when you try to use those numbers in a stream and suddenly your precision disappears:
Code:
What happened? You might not know that along with a host of other attributes, like std::dec, std::hex, or std::oct, streams and stringstreams in C++ have an associated maximum decimal precision. In this case, you got caught in the trap of a default precision of four decimal places. The easy solution: simply set a nice large precision before your stream conversion:
Code:
In this case, that extra precision is the vital difference between reaching the town you meant to find and reaching your correct destination. Enjoy.
C++ Stream Precision
Say that you're writing a program that converts GPS NMEA strings into decimal coordinates. The output of your GPS receiver, grabbed by a serial-port input program, might look something like this:
Code:
$GPRMC,230632.000,A,4043.7187,N,07359.3728,W,0.23,189.48,070809,,*10
Of course, this is not particularly useful, so we will use strtok and some loop magic to create two variables, lat and lon. Here's how they'll be defined:
Code:
double lat, lon;
lat = strtod(lat_string,NULL)/100.0;
lon = strtod(lon_string,NULL)/100.0;
Code:
std::cout << lat << ", " << lon << std::endl;
// Surprise! The output is "40.4372, 73.5937"
What happened? You might not know that along with a host of other attributes, like std::dec, std::hex, or std::oct, streams and stringstreams in C++ have an associated maximum decimal precision. In this case, you got caught in the trap of a default precision of four decimal places. The easy solution: simply set a nice large precision before your stream conversion:
Code:
std::cout.precision(10);
std::cout << lat << ", " << lon << std::endl;
// Whew. As it should be, the output is "40.437187, 73.593728"
In this case, that extra precision is the vital difference between reaching the town you meant to find and reaching your correct destination. Enjoy.