Home > other >  Float to char array in C
Float to char array in C

Time:01-22

I trying to merge all members of a float array in a char array.

This is float array :

float myFloatArray[2] = {10,20};

And this is char array :

char myCharArray[32];

I want to set char array like "1020"

in C# i can do it like this;

string myStr =  myFloatArray[0]   myFloatArray[1];

but how can i do this in C?

CodePudding user response:

If you only have two numbers to be converted, then you can simply write

snprintf(
    myCharArray, sizeof myCharArray,
    "%.0f%.0f",
    myFloatArray[0],
    myFloatArray[1]
);

Here is a working example program:

#include <stdio.h>

int main(void)
{
    float myFloatArray[2] = {10,20};
    char myCharArray[32];
    snprintf(
        myCharArray, sizeof myCharArray,
        "%.0f%.0f",
        myFloatArray[0],
        myFloatArray[1]
    );

    printf( "%s\n", myCharArray );
}

This program has the following output:

1020

CodePudding user response:

A simple way is to use sprintf to convert the first and second elements of the float array to strings, and concatenate them into the char array. The "%.0f" format specifier tells sprintf to format the float value as an integer.

sprintf(myCharArray, "%.0f%.0f", myFloatArray[0], myFloatArray[1]);

Also notice the answer provided in this post where snprintf is suggested for safety reasons.

snprintf(myCharArray, sizeof(myCharArray), "%.0f", myFloatArray[0]);
snprintf(myCharArray strlen(myCharArray), sizeof(myCharArray)-strlen(myCharArray), "%.0f", myFloatArray[1]);
  • Related