Convert float variable to string

本文介绍了一种将浮点数转换为字符串的方法,并特别关注了小数点后三位的有效精度处理。该方法通过一系列数学运算确保数值精度,并正确处理小于1.0的数值情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值