user1106106
user1106106

Reputation: 277

Function atof() rounds its result to integer part

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

Answers (5)

Micka
Micka

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

captainB
captainB

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

Ashish Kasma
Ashish Kasma

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

HWende
HWende

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

Luchian Grigore
Luchian Grigore

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

Related Questions