C Program to convert a number to a string

CServer Side ProgrammingProgramming

In this section we will see how to convert a number (integer or float or any other numeric type data) to a string.

The logic is very simple. Here we will use the sprintf() function. This function is used to print some value or line into a string, but not in the console. This is the only difference between printf() and sprintf(). Here the first argument is the string buffer. where we want to save our data.

Input: User will put some numeric value say 42.26
Output: This program will return the string equivalent result of that number like "42.26"


Step 1: Take a number from the user
Step 2: Create an empty string buffer to store result
Step 3: Use sprintf() to convert number to string
Step 4: End

Example Code

 Live Demo

main() {
   char str[20];    //create an empty string to store number
   float number;
   printf("Enter a number: ");
   scanf("%f", &number);
   sprintf(str, "%f", number);   //make the number into string using sprintf function
You have entered: %s", str); }


Enter a number: 46.3258
You have entered: 46.325802
Updated on 30-Jul-2019 22:30:25