将float转换为字符串而不使用sprintf()

aud*_*tic 6 c memory string floating-point printf

我正在编写基于微控制器的应用程序,我需要将其转换为float字符串,但我不需要与sprintf()相关的繁重开销.有没有雄辩的方法来做到这一点?我不需要太多.我只需要2位数的精度.

enh*_*lep 5

尝试这个。它应该很好而且很小。我直接输出了字符串——做一个 printf,而不是一个 sprintf。我会让你为返回字符串分配空间,以及将结果复制到其中。

// prints a number with 2 digits following the decimal place
// creates the string backwards, before printing it character-by-character from
// the end to the start
//
// Usage: myPrintf(270.458)
//  Output: 270.45
void myPrintf(float fVal)
{
    char result[100];
    int dVal, dec, i;

    fVal += 0.005;   // added after a comment from Matt McNabb, see below.

    dVal = fVal;
    dec = (int)(fVal * 100) % 100;

    memset(result, 0, 100);
    result[0] = (dec % 10) + '0';
    result[1] = (dec / 10) + '0';
    result[2] = '.';

    i = 3;
    while (dVal > 0)
    {
        result[i] = (dVal % 10) + '0';
        dVal /= 10;
        i++;
    }

    for (i=strlen(result)-1; i>=0; i--)
        putc(result[i], stdout);
}
Run Code Online (Sandbox Code Playgroud)

  • 意识到这是一篇较旧的帖子,路人应该明白这个函数对于负数不能正常工作。 (2认同)

Esc*_*her 5

这是一个针对嵌入式系统优化的版本,它不需要任何 stdio 或 memset,并且具有低内存占用。您负责传递一个用零初始化的字符缓冲区(带有指针p),您想在其中存储字符串,并定义CHAR_BUFF_SIZE何时创建所述缓冲区(因此返回的字符串将以空字符结尾)。

static char * _float_to_char(float x, char *p) {
    char *s = p + CHAR_BUFF_SIZE; // go to end of buffer
    uint16_t decimals;  // variable to store the decimals
    int units;  // variable to store the units (part to left of decimal place)
    if (x < 0) { // take care of negative numbers
        decimals = (int)(x * -100) % 100; // make 1000 for 3 decimals etc.
        units = (int)(-1 * x);
    } else { // positive numbers
        decimals = (int)(x * 100) % 100;
        units = (int)x;
    }

    *--s = (decimals % 10) + '0';
    decimals /= 10; // repeat for as many decimal places as you need
    *--s = (decimals % 10) + '0';
    *--s = '.';

    while (units > 0) {
        *--s = (units % 10) + '0';
        units /= 10;
    }
    if (x < 0) *--s = '-'; // unary minus sign for negative numbers
    return s;
}
Run Code Online (Sandbox Code Playgroud)

在 ARM Cortex M0 和 M4 上测试。正确绕圈。