Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a char to double [closed]

Tags:

c

Ok, I have a char that is a number. How could I convert it into a double?

char c;

I've tried (double)c, but it converts to zero.

Any ideas?

like image 842
Frank Avatar asked Nov 16 '12 20:11

Frank


People also ask

Can char convert to double?

We can convert a char array to double by using the std::atof() function.

Can you convert char to string?

You can use String(char[] value) constructor to convert char array to string. This is the recommended way.


2 Answers

if you have a null terminated string that you wish to convert to double use atof:

const char *str = "3.14";
double x = atof(str);
printf("%f\n", x); //prints 3.140000

If you have a single character, casting should work:

char c = 'a'; //97 in ASCII
double x = (double)c; 
printf("%f\n", x); //prints 97.000000

If the character is zero then it print zeros of course:

char c = '\0';
double x = (double)c; 
printf("%f\n", x); //prints 0.000000

Note: atof and similar functions don't detect overflows and return zero on error, so there's no way to know if it failed (not sure if it sets errno), see also Keith's comments about undefined behaviour for certain values, so the point is you should use strtol for converting from strings to int and strtod for converting to double those have much better error handling:

const char *str = "3.14";
double x = strtod(str, NULL);
like image 161
iabdalkader Avatar answered Oct 11 '22 23:10

iabdalkader


To answer the question you asked:

#include <stdio.h>
int main(void) {
    char c = 42;
    // double d = (double)c; The cast is not needed here, because ...
    double d = c;    // ... the conversion is done implicitly.
    printf("c = %d\n", c);
    printf("d = %f\n", d);
    return 0;
}

char is an integer type; its range is typically either -128 to +127 or 0 to +255. It's most commonly used to store character values like 'x', but it can also be used to store small integers.

But I suspect you really want to know how to convert a character string, like "1234.5", to type double with the numeric value 1234.5. There are several ways to do this.

The atof() function takes a char* that points to a string, and returns a double value; atof("1234.5") returns 1234.5. But it does no real error handing; if the argument is too big, or isn't a number, it can behave badly. (I'm not sure of the details of that, but I believe its behavior is undefined in some cases.)

The strtod() function does the same thing and is much more robust, but it's more complex to use. Consult your system's documentation (man strtod if you're on a Unix-like system).

And as Coodey said in a comment, you need to make your question more precise. An example with actual code would have made it easier to figure out just what you're asking.

like image 23
Keith Thompson Avatar answered Oct 11 '22 22:10

Keith Thompson