單片機浮點數轉字符串可以使用 stdio.h 中sprintf函數,但代碼體積和RAM佔用空間比較大。自己寫的程序又不太好。在學習GPS數據解析過程中用到了LeiOuYang的GPS解析庫,在其中有浮點數轉字符串函數,現推薦給大家。
一下是完整的基於KEIL C51 的C文件:
//#include <string.h>
//#include <stdio.h> //使用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<-0.000000000000000001)
{
*pstr = '-';
++pstr;
value = -value;
}
tvalue = (int)value%int_pow(10,intgr);
while(intgr)
{
c = DIGITAL_TO_CHAR(tvalue/int_pow(10,intgr-1));
if( !zeroflag && '0'==c )
{
tvalue = tvalue%int_pow(10,intgr-1);
--intgr;
continue;
}
zeroflag = 1;
*pstr = c;
tvalue = tvalue%int_pow(10,intgr-1);
--intgr;
++pstr;
}
if( !zeroflag ) *pstr++ = '0';
/* 如果小數位數爲0,則返回整數部分 */
if(0==dec)
{
*pstr = '\0';
return 1;
}
*pstr++ = '.';
tm = (unsigned int)int_pow(10,dec);
tvalue = (unsigned int)( ( (unsigned int)((value-(unsigned int)value)*tm) )%tm );
while(dec)
{
tm = int_pow(10,dec-1);
*pstr = DIGITAL_TO_CHAR(tvalue/tm);
tvalue = tvalue%tm;
--dec;
++pstr;
}
*pstr = '\0';
return 1;
}
void main()
{
int a;
// sprintf(DispBuff,"%.1f",10.1);
a=float_to_string(10.1,DispBuff,3,1);
while(1);
}
編譯結果:
仿真結果:
而使用sprintf的程序,
#include <stdio.h>
unsigned char DispBuff[5];
void main()
{
sprintf(DispBuff,"%.1f",10.1);
while(1);
}
編譯結果: