# Thread: Math Help! Converting Doubles

1. ## Math Help! Converting Doubles

Alright so here's my problem: I'm doing some math functions that require decimal places, so i'm using double right now to define the varibles. However i'm using an LCD display that requires the information to be in Char format for me to correctly display them. So how can I convert a decimal number, such as 4.294882, to char format? And in that instance i would need each number to be in an array of chars. So i need to convert a 32 bit double number to 8 individual chars so that i can output them. Is it possible? I don't know...but if it is you guys should help!! Thanks a bunch

~Mike

p.s. If this isn't possible that would be good to know too, but i'm pretty sure it is possible...i just wish i knew how to do it!

2. Oh, it's definately possible. But I don't know of any library function that can do it for you. You'll have to write your own.

You'll need to know where the deciaml place is. To do that, you could cast the double as an int and store the number of digits in the result.

Then, you could use that answer to single out the digits before the decimal point and converting a sinlge digit to ASCII is very simple. Just add 48. When you get to the decimal place, just multiply the double by 10 and cast it into an int until you've taken care of all the digits. Think you get it?

3. This topic comes up quite a bit... "How do I convert X to Y?" Use a stringstream:

Code:
```#include <sstream>
#include <iostream>

using namespace std;

int main()
{
stringstream sstr;
double d =  4.294882;
char cstr[9];

// Store double into string stream
sstr.precision(7);
sstr << d;

// Extract sizeof(cstr)-1 characters from the string stream and store in cstr
sstr.get(cstr,sizeof(cstr));

// Display contents of character array
cout << cstr << endl;

return 0;
}```
Depending of the value of the double and how many decimal places it needs to have, you may have to fiddle around with the value passed to the precision function and possibly add a call to the stream's width function as well.

4. Alright, thanks for those ideas. I was also told that i could use sprintf?
Code:
```int main(void)
{
char display[9];
double value = 4.294882;
sprintf(display, "%.8g", value);
puts(display); /* LCD function */
return 0;
}```
That's what someone told me, but my output was 'g' for some reason. Alright i'll try them and let you know, thanks for the help.

5. %g is an invalid specifier, I think.

6. Alright, so would you happen to know what the correct specifier would be? I'm not too familiar with sprintf....i have an eight digit double decimal number that i need to get into an array of chars. Thanks!

7. %f. It works for both floats and doubles.

8. Originally Posted by Jaken Veina
%f. It works for both floats and doubles.
so does %g

Note that, depending on the magnitude of the number, either %f or %g can result in more chars than indicated by the specifier.

Regards,

Dave