码迷,mamicode.com
首页 > 其他好文 > 详细

浮点数转换成字符串函数

时间:2014-07-02 14:54:49      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   io   div   

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

浮点数转换成字符串函数,布布扣,bubuko.com

浮点数转换成字符串函数

标签:style   blog   color   for   io   div   

原文地址:http://www.cnblogs.com/craftor/p/3820027.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!