stm32的float转字符串
在stm编程调试的时候,一些参数是float类型的,不论是oled显示还是串口输出都不是很方便,这里提供了两种方法进行float转str
不使用sprintf
void float_to_string(float f,char *str, int precision)
{
float ff;
int a,b,c,k,l=0,m,i=0,j;
ff = f;
if(f<0.0)
{
str[i++]='-';
f*=-1;
}
a=f;
f-=a;
k = 0;
while(1)
{
l = pow(10,k);
m = a/l;
if(m==0)
{
break;
}
k++;
}
k--;
for(l=k+1;l>0;l--)
{
b = pow(10,l-1);
c = a/b;
str[i++]=c+48;
a%=b;
}
if(precision != 0)
str[i++] = '.';
for(l=0;l<precision;l++)
{
f*=10.0;
b = f;
str[i++]=b+48;
f-=b;
}
str[i]='\0';
}
使用printf
float a=12.1047;
char ch[100];
sprintf(ch,"%f",a);