转换后的字符串未能包含正确的浮点值

converted string failed to contain correct values of float

我在将 float 转换为 char* 时遇到问题。
我写了一个函数,它将 float 的整数部分放入字符串中,然后放入十进制值。我需要它保留两位小数。但有些事情是非常错误的。它要么输出整数值,要么输出小数点后 1 位。有人可以指导我吗? 下面是我的尝试

void float_to_str(char *str, float f, char size)
{

    char pos;  // position in string

    char len;  // length of decimal part of result

    char* curr;  // temp holder for next digit

    int value, i  ;  // decimal digit(s) to convert
   float temp;
    pos = 0;  // initialize pos, just to be sure

    value = ( int )f;  // truncate the floating point number
    snprintf( curr, sizeof(curr), "%d", value);

    strncmp( str, curr, strlen( curr ) );

    // now str array has the digits before the decimal

    if (f < 0 )  // handle negative numbers
    {
        f *= -1;
        value *= -1;
    }

    len = strlen( str );  
    pos = len;  // position the pointer to the end of the integer part
    str[pos++] = '.';  // add decimal point to string

    f = f -( float ) value + 0.005;
    printf( " the value of f = %f\n", f );

        for( i = 0; i < size; ++i )
        {

           temp = f* 10;
            value = ( int )temp ;
            snprintf( curr, sizeof(curr),"%d", value );
            str[ pos++ ] = *curr;
        }

    str[ pos ] = '/0';
    printf("  debug --> the string is %s \n", str );  // prints only 5 instead of 6455.56 
 }

int main()
{

float test = 555564.5555;
char arr[ 40 ];
memset(arr, 0, 40 );
FloatToStringNew( arr,test, 2 );

printf( " the  float to string is %s", arr ); // OUT Put is  5 which is wrong
return 0;
}

整个float_to_string可以简化为(如BLUEPIXY所建议):

void float_to_str(char *str, float f, char size)
{
    sprintf(str, "%.*f", size, f);
}

但是,如果您对代码中的错误感兴趣,它在 for 循环中:

    for( i = 0; i < size; ++i )
    {

       temp = f* 10;  // Value of f stays the same in every iteration
        value = ( int )temp ;
        snprintf( curr, sizeof(curr),"%d", value );
        str[ pos++ ] = *curr;
    }

修复:

    for( i = 0; i < size; ++i )
    {

        f = f * 10;  // Modify f each iteration
        value = ( int )f; 
        snprintf( curr, sizeof(curr),"%d", value );
        str[ pos++ ] = *curr;
        f = f - (int)f; // Remove the integer part 
    }

编辑:

函数中还有一些其他的东西需要修复:

strncmp 应该是 strcpy

pos 应为 intsize_t

类型

curr 应该是数组而不是指针。

main 的调用应该是 float_to_string,而不是 FloatToStringNew

当我编译时出现警告时,编译器帮助我找到了它们(我在 gcc 中使用 -Wall)。