开发者

Converting a string to double

I have 开发者_如何学Pythonthe following code which doesn't run properly.

char dec_number[300];
dec_number[0]='\0';
//some code that reads a decimal number and stores it in dec_number
//I get in dec_number 0.19

When I printed the value, I get 0.19.

After that I want to multiply it with something so I need to store it in double.

I convert it to double using double k=atod(dec_number); and k=strtod(dec_number, NULL);. But I get 9716 or something large but nothing near 0.19.

What have I done wrong? Any suggestions? Thank you.


You are converting it incorrectly, apparently. Nobody here is has telepathic abilities (I presume), so there's no way to say what you are doing wrong until you show us your code where you convert your string to double.

Anyway, the proper way to convert a string to double is to use strtod function.

char *end;
double d = strtod(dec_number, &end);
/* Perform error handling be examining `errno` and, if necessary, `end` */

Are you using strtod?


Did you #include <stdlib.h>? If not it might be assuming atof or strtod should return an int and reading from whatever location functions that return integers normally return, which will result in nonsense answers.


just use atof function:

#include <cstdlib>

char *str_number = "0.19";
double val = atof(str_number);


Without seeing more code, my guess is that you're not null-terminating dec_number when you read in the number.


With null-terminated strings atof and strtod do what you want but are very forgiving.
Should you not want to accept strings like "42life" as valid you can wrap strtod like this:

double strict_strtod(char* str)
{
    char* endptr;
    double value = strtod(str, &endptr);
    if (*endptr) return 0;
    return value;
} 


Try this:

double k;

sscanf(dec_number,"%lf",&k);
// k is the double value stored in the buffer

sprintf(buffer,"%f",k)
// buffer is now containing the representation of k


Use parseFloat(), it should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜