如何将float
值转换char*
为C
语言?
7 回答
char buffer[64];
int ret = snprintf(buffer, sizeof buffer, "%f", myFloat);
if (ret < 0) {
return EXIT_FAILURE;
}
if (ret >= sizeof buffer) {
/* Result was truncated - resize the buffer and retry.
}
这将存储 in 的字符串表示myFloat
形式myCharPointer
。不过,请确保绳子足够大以容纳它。
snprintf
是一个更好的选择,sprintf
因为它保证它永远不会超过您在参数 2 中提供的缓冲区的大小。
char array[10];
sprintf(array, "%f", 3.123);
sprintf:(来自 MSDN)
在阿杜诺:
//temporarily holds data from vals
char charVal[10];
//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(123.234, 4, 3, charVal);
monitor.print("charVal: ");
monitor.println(charVal);
Long after accept answer.
Use sprintf()
, or related functions, as many others have answers suggested, but use a better format specifier.
Using "%.*e"
, code solves various issues:
The maximum buffer size needed is far more reasonable, like 18 for
float
(see below). With"%f"
,sprintf(buf, "%f", FLT_MAX);
could need 47+.sprintf(buf, "%f", DBL_MAX);
may need 317+char
.Using
".*"
allows code to define the number of decimal places needed to distinguish a string version offloat x
and it next highestfloat
. For deatils, see Printf width specifier to maintain precision of floating-point valueUsing
"%e"
allows code to distinguish smallfloat
s from each other rather than all printing"0.000000"
which is the result when|x| < 0.0000005
.
Example usage
#include <float.h>
#define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4 +1)
// - d . dddddddd e - dddd \0
char buf[FLT_STRING_SIZE];
sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);
Ideas:
IMO, better to use 2x buffer size for scratch pads like buf[FLT_STRING_SIZE*2]
.
For added robustness, use snprintf()
.
As a 2nd alterative consider "%.*g"
. It is like "%f"
for values exponentially near 1.0 and like "%e"
for others.
char* str=NULL;
int len = asprintf(&str, "%g", float_var);
if (len == -1)
fprintf(stderr, "Error converting float: %m\n");
else
printf("float is %s\n", str);
free(str);
typedef union{
float a;
char b[4];
} my_union_t;
您可以逐字节访问浮点数据值,并通过 8 位输出缓冲区(例如 USART)将其发送而无需强制转换。
char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);