Reputation: 277
Why does atof round "14718.5084" to 14718.5? Is there a way to prevent that (i.e. get the whole number 14718.5084)?
code:
double latitude=atof("14718.5084");
std::cout <<"latitude test "<<latitude<< "\n";
and the output is:
latitude test 14718.5
thanks
Upvotes: 0
Views: 4648
Reputation: 20130
I had an slightly different problem, but it fits the headline. atof looked like rounding to integer part and it wasn't a output precision problem. My solution was to change the locale settings of my ubuntu installation. Decimals were separated by comma instead of point.
try this code (comma instead of point):
double latitude=atof("14718,5084");
std::cout <<"latitude test "<<latitude<< "\n";
if it outputs the correct floating point number (maybe separated by point), you should change your locale settings to english or work with comma floating values in your data (e.g. german locale settings)
Upvotes: 0
Reputation: 31
Locale settings can add even more confusion, as apparently they're not always in effect consistently throughout the toolchain.
E.g. I ran into the problem that point separted values were rounded to int by atof (e.g. 0.85 -> 0 ) because the locale demanded comma-separted values. But at the same time, comma-separated values weren't accepted by the debugger IDE either (e.g. when attempting to change variable values during debugging..).
Upvotes: 1
Reputation: 3642
#include <limits>
double latitude=atof("14718.5084");
typedef std::numeric_limits< double > dbl;
std::cout <<"latitude test ";
std::cout.precision(dbl::digits10);
std::cout<<latitude<< "\n";
Upvotes: 1
Reputation: 1705
Try this code to see it does exactly what you want:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char input [256];
printf("Enter something: ");
gets(input);
printf("Result: %f\n", atof(input));
return 0;
}
Maybe you lost the digits when printing...
Try this:
double latitude=atof("14718.5084");
std::cout.precision(9);
std::cout <<"latitude test "<< latitude << "\n";
Upvotes: 6
Reputation: 258598
Because atof
returns a double
, which you're converting to a float
. (I'm guessing this is what you're doing).
Also, 14718.5084
can't be represented exactly. For example:
double f = 14718.5084;
gives me f == 14718.508400000001
.
Upvotes: 2