简体   繁体   English

在 C 上将浮点数转换为字符数组

[英]Convert a float number to char array on C

I am trying to convert a float number to a char array.我正在尝试将浮点数转换为 char 数组。 sprintf() will not work for me and neither will dtostrf . sprintf()对我不起作用, dtostrf也不会。 Since I have a limit in the decimal number (it is 5) I tried this:因为我有十进制数的限制(它是 5)我试过这个:

    int num = f;
    int decimales = (f-num)*10000;

Everything worked fine until I typed the number 123.050.一切正常,直到我输入数字 123.050。 Instead of giving me the decimal part as "0.50" it gives me a 5000, because it does not count the 0 now that my "decimal" variable is an int .它没有给我小数部分作为“0.50”,而是给了我 5000,因为现在我的“小数”变量是int ,它不计算 0。

Is there any other way to convert it?有没有其他方法可以转换它?

Use %04d in printf()printf()中使用%04d

 const int D4 = 10000;

 double f = 123.050;
 int i = round(f*D4);
 int num = i / D4;
 int decimales = i % D4;
 printf("%d.%04d\n", num, decimales);

gives

123.0500

If you worry about an int overflow (since we multiply the number by 10000 ), use long , or long long instead...如果您担心int溢出(因为我们将数字乘以10000 ),请改用longlong long ...

To save decimals in a string including the leading zero(es)将小数保存在包含前导零的字符串中

char sdec[5];
sprintf(sdec, "%04d", decimales);

sdec contains the decimals, including the leading zero. sdec包含小数,包括前导零。

(see also Is floating point math broken? ) (另请参阅浮点数学是否损坏?

You want a quick and dirty way to produce a string with the decimal representation of your float without linking sprintf because of space constraints on an embedded system.由于嵌入式系统的空间限制,您需要一种快速而肮脏的方法来生成具有浮点数的十进制表示的字符串,而无需链接sprintf The number of decimals is fixed.小数位数是固定的。 Here is a proposal:这是一个建议:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *ftoa(char *dest, size_t size, double val, int dec) {
    char *p = dest;
    char *q = dest + size;
    long long mul = 1;
    long long num;
    int i;
    if (size == 0)
        return NULL;
    *--q = '\0';
    if (size == 1)
        goto fail;
    if (val < 0) {
        val = -val;
        if (p >= q)
            goto fail;
        *p++ = '-';
    }
    for (i = 0; i < dec; i++) {
        mul *= 10;
    }
    num = (long long)(val * mul + 0.5);
    for (i = 1; i < dec + 2 || num > 0; i++) {
        if (p >= q)
            goto fail;
        *--q = '0' + (num % 10);
        num = num / 10;
        if (i == dec) {
            if (p >= q)
                goto fail;
            *--q = '.';
        }
    }
    memmove(p, q, dest + size - q);
    return dest;
fail:
    return memset(dest, '*', size - 1);
}

int main(int argc, char *argv[]) {
    char buf[24];

    for (int i = 1; i < argc; i++) {
        double d = strtod(argv[i], NULL);
        int dec = 5;
        if (i + 1 < argc)
            dec = atoi(argv[++i]);
        printf("%s\n", ftoa(buf, sizeof buf, d, dec));
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM