浮点数转换成字符串函数

方法1:

转载地址:http://www.cnblogs.com/craftor/p/3820027.html


sprintf函数太大,在STM8上面根本不敢用,动不动就.text overflow。为了将采集的数值通过串口上传到计算机,只能自己写了一个浮点数转换成字符串的函数:

复制代码
#include <stdio.h>
#include <stdint.h>

static char table[]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

void num2char(char *str, double number, uint8_t g, uint8_t l)
{
    uint8_t i;
    int temp = number/1;
    double t2 = 0.0;
    for (i = 1; i<=g; i++)
    {
        if (temp==0)
            str[g-i] = table[0];
        else
            str[g-i] = table[temp%10];
        temp = temp/10;
    }
    *(str+g) = '.';
    temp = 0;
    t2 = number;
    for(i=1; i<=l; i++)
    {
        temp = t2*10;
        str[g+i] = table[temp%10];
        t2 = t2*10;
    }
    *(str+g+l+1) = '\0';
}


int main(int argc, char const *argv[])
{
    char str[20];
    num2char(str, 23.56821312, 8, 10);
    printf("%s\n", str);
    return 0;
}
复制代码

测试结果如下:

00000023.5682131

方法2:
unsigned char tmp[4];
uint32_t zhengshu, xiaoshu;
float a=12.3456;
//输出浮点数到瑞丽RSI240128串口屏,其中sprintf函数把浮点数转换成字符串存放在字符串数组tmp[]里
sprintf((char*)tmp,"%4.1f",-3.1415);//Temperature[0]
print_string_xy(0x00,0,20,tmp);


//取浮点数得整数和小数部分,并分别输出到瑞丽RSI240128串口屏
zhengshu=(int)a;
xiaoshu=(int)((a-zhengshu)*10.0);
print_U32(0x00,zhengshu);
print_U32(0x00,xiaoshu);



  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值