将浮点数转换为字符串

2022-01-09 00:00:00 floating-point c c++

如何在没有库函数 sprintf 的情况下将浮点整数转换为 C/C++ 中的字符串?

How can I convert a floating point integer to a string in C/C++ without the library function sprintf?

我正在寻找一个函数,例如char *ftoa(float num)num 转换为字符串并返回.

I'm looking for a function, e.g. char *ftoa(float num) that converts num to a string and returns it.

ftoa(3.1415) 应该返回 "3.1415".

推荐答案

当你处理 fp 数字时,它会变得非常复杂,但算法很简单,类似于 edgar holleis 的答案;赞!它很复杂,因为当您处理浮点数时,根据您选择的精度,计算会有些偏差.这就是为什么将浮点数与零进行比较不是好的编程习惯.

When you're dealing with fp numbers, it can get very compex but the algorithm is simplistic and similar to edgar holleis's answer; kudos! Its complex because when you're dealing with floating point numbers, the calculations will be a little off depending on the precision you've chosen. That's why its not good programming practice to compare a float to a zero.

但是有一个答案,这是我实现它的尝试.在这里,我使用了一个容差值,因此您最终不会计算太多小数位,从而导致无限循环.我确信那里可能有更好的解决方案,但这应该有助于您更好地了解如何做到这一点.

But there is an answer and this is my attempt at implementing it. Here I've used a tolerance value so you don't end up calculating too many decimal places resulting in an infinite loop. I'm sure there might be better solutions out there but this should help give you a good understanding of how to do it.

char fstr[80];
float num = 2.55f;
int m = log10(num);
int digit;
float tolerance = .0001f;

while (num > 0 + precision)
{
    float weight = pow(10.0f, m);
    digit = floor(num / weight);
    num -= (digit*weight);
    *(fstr++)= '0' + digit;
    if (m == 0)
        *(fstr++) = '.';
    m--;
}
*(fstr) = '';

相关文章