Converting float to char*

后端 未结 7 752
野性不改
野性不改 2021-02-04 01:54

How can I convert a float value to char* in C language?

7条回答
  •  生来不讨喜
    2021-02-04 02:33

    Long after accept answer.

    Use sprintf(), or related functions, as many others have answers suggested, but use a better format specifier.

    Using "%.*e", code solves various issues:

    • The maximum buffer size needed is far more reasonable, like 18 for float (see below). With "%f", sprintf(buf, "%f", FLT_MAX); could need 47+. sprintf(buf, "%f", DBL_MAX); may need 317+

    • Using ".*" allows code to define the number of decimal places needed to distinguish a string version of float x and it next highest float. For deatils, see Printf width specifier to maintain precision of floating-point value

    • Using "%e" allows code to distinguish small floats from each other rather than all printing "0.000000" which is the result when |x| < 0.0000005.

    Example usage

    #include 
    #define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4   +1)
                         //  - d .  ffffdffffffffd           e - ffffdd \0
    
    char buf[FLT_STRING_SIZE];
    sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);
    

    Ideas:
    IMO, better to use 2x buffer size for scratch pads like buf[FLT_STRING_SIZE*2].
    For added robustness, use snprintf().


    As a 2nd alterative consider "%.*g". It is like "%f" for values exponentially near 1.0 and like "%e" for others.

提交回复
热议问题