Pages

Aug 8, 2011

Convert double to char[] array in C/C++

Convert double to char[] in C/C++

How to Convert Double to Char[] Array in C/C++



How to Convert Double to Char[] Array in C/C++


It is very easy to convert double to char[] array in C or C++, we can do it by using sprintf method.
If you have no idea about sprintf , then please take a look at sprintf in cplusplus.com .

In below code , we are trying to utilize the the sprintf to get the double to get back in the char[] array in C or C++:


/* | Author     : Alim Ul Karim               |
   | Email      : auk.junk@live.com           |
   | Portfolio  : auk-port.webs.com           |
   | Blog       : bit.ly/auk-blog             |
   |------------------------------------------|
   | Code tested on CodeBlocks , GCC Compiler |
   | Example of Double to Char[] array        |
   |------------------------------------------|
 */


#include <stdio.h>

int main(){
    char c[10]; //becuase double is 8 bytes in GCC compiler but take 10 for safety 
    double d = -234.2341;

    sprintf(c , "%lf" , d);
    printf("output :: |%s|\n" , c);
}

How to Convert Double to Char[] array in C/C++
It is not very hard to convert double to char[] array in c or C++ , we can do it by using sprintf method.

How to convert Double to char[] array using sprintf in C/C++


Related Links:


Search Labels:

Double to Char[] array,

Convert Double to Char[] array, 

Convert Double to Char[] array in C

Convert Double to Char[] array in C++ ,

Convert

double

to

char[]

6 comments:

  1. great , and very easy....

    ReplyDelete
  2. I looked all over the web for this and people had posted many complex ways of doing it. I saw your blog and I am glad I didn't think it was rubbish. Hats off to you! Thanks a lot! You saved my day!

    ReplyDelete
  3. Thanks I like to make things simple.

    ReplyDelete
  4. Nice :)! I bothered to write my own code, but this is just great!

    ReplyDelete
  5. Number of bytes for a double is NOT number of digits in base 10 ==> buffer overflow...
    Use char c[32] instead.

    And the 'l' in %lf is useless. Should be "%f".

    ReplyDelete
  6. no it shouldn't.... it must be "%lf" and you can try char c[10]

    ReplyDelete