Convert float variable to string

来源:互联网 发布:linux下gcc编译器 编辑:程序博客网 时间:2024/05/01 01:34
//Warning: if the float variable is larger than the 10000,the decimal part digit will be not precise(but the func logic is correct)!!!


int FtoStr(float f, char *str)
{
char buf[20] = {0};
char *pos = buf;
int tmp;


if(NULL == str) return -1;
if(f < 0) {
f = -f;
*str++ = '-';
}


tmp = ((int)(f * 10000) % 10) >= 5 ? (f * 1000) + 1 : (f * 1000); //keep 3 decimal precision digit
do {
if(pos == buf + 3)//insert the decimal point position
*pos++ = '.';
*pos++ = tmp % 10 + '0';


}while(tmp /= 10);//check whether the copied char is the last char or not
while(pos < buf + 3)//less than 1.0
*pos++ = '0';


if(pos == buf + 3){
*pos++ = '.';
*pos++ = tmp +'0';
}
while(pos > buf)
*str++ = *--pos;
*str = '\0';
return 0;

}

0 0
原创粉丝点击