Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert a floating point number to string in C
In C, converting a floating point number to a string is accomplished using the sprintf() function. This function works similarly to printf(), but instead of printing to the console, it writes the formatted output to a string buffer.
Syntax
int sprintf(char *str, const char *format, ...);
Parameters:
-
str− Pointer to the destination string buffer -
format− Format string specifier (e.g., "%f" for float) -
...− Variable arguments to be formatted
Example 1: Basic Float to String Conversion
The following example demonstrates converting a floating point number to a string using sprintf() −
#include <stdio.h>
int main() {
char str[20];
float number = 42.26;
sprintf(str, "%f", number);
printf("Original number: %.2f<br>", number);
printf("Converted string: %s<br>", str);
return 0;
}
Original number: 42.26 Converted string: 42.260002
Example 2: Controlling Decimal Precision
You can control the number of decimal places using format specifiers −
#include <stdio.h>
int main() {
char str[20];
float number = 123.456789;
sprintf(str, "%.2f", number); // 2 decimal places
printf("With 2 decimals: %s<br>", str);
sprintf(str, "%.4f", number); // 4 decimal places
printf("With 4 decimals: %s<br>", str);
return 0;
}
With 2 decimals: 123.46 With 4 decimals: 123.4568
Example 3: User Input Conversion
This example takes user input and converts the floating point number to string format −
#include <stdio.h>
int main() {
char str[50];
float number;
printf("Enter a floating point number: ");
scanf("%f", &number);
sprintf(str, "%.3f", number);
printf("You entered: %s<br>", str);
return 0;
}
Enter a floating point number: 46.3258 You entered: 46.326
Key Points
- Ensure the destination buffer is large enough to hold the converted string
- Use format specifiers like
%.2fto control decimal precision -
sprintf()returns the number of characters written (excluding null terminator)
Conclusion
Converting floating point numbers to strings in C is efficiently handled by sprintf(). This function provides precise control over formatting and is essential for string manipulation in C programming.
