单片机浮点数转字符串可以使用 stdio.h 中sprintf函数,但代码体积和RAM占用空间比较大。自己写的程序又不太好。在学习GPS数据解析过程中用到了LeiOuYang的GPS解析库,在其中有浮点数转字符串函数,现推荐给大家。
一下是完整的基于KEIL C51 的C文件:
//#include //#include //使用sprintf时取消该注释
#define DIGITAL_TO_CHAR(x) ( (x)+'0' )
unsigned char DispBuff[5];
/* 多次方 */
static int int_pow(int value, unsigned int count)
{
int v = 1;
while(count--)
v = v*value;
return v;
}
/* 浮点数转换为字符串,包括整数转换为字符串
* intgr指定整数位个数,dec指定小数位个数
* 自动去除前面的0,小数点后面的0不会舍去
*/
static unsigned char float_to_string(double value, char* pdest, unsigned int intgr, unsigned int dec)
{
char* pstr = (void*)0;
double fvalue = 0.0;
char c = 0;
unsigned int tvalue = 0;
unsigned char zeroflag = 0;
unsigned int tm = 0;
if( (void*)0==pdest || 0==intgr ) return 0;
if(dec>9) dec = 9;
if(1==intgr) zeroflag = 1;
pstr = pdest;
if(value
编译结果:
仿真结果:
而使用sprintf的程序,
#include unsigned char DispBuff[5];
void main()
{
sprintf(DispBuff,"%.1f",10.1);
while(1);
}
编译结果: