You can use "snprintf" to accomplish this.
int snprintf(char *str, size_t size, const char *format, ...);
Upon successful return, this function returns the number of characters printed (not including the trailing '\0' used to end output to strings). The function snprintf() does not write more than size characters (including the trailing '\0'). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '\0') which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. (See also below under NOTES.) If an output error is encountered, a negative value is returned.
You will notice in this example that if you run it the string is reported as truncated. This is because by default the %f format has a percision of 6 decimal places. Change %f to %.2f and rerun it.
-
#include <stdio.h>
-
-
#define SIZE 10
-
-
int main(void)
-
{
-
char buf[SIZE];
-
int result = 0;
-
float value = 154.78;
-
-
result = snprintf(buf, SIZE, "%f", value);
-
if (result >= SIZE)
-
printf("The string has been truncated\n");
-
-
printf("The string value of the floating value = %s\n", buf);
-
-
return 0;
-
}
-