Home  >  Q&A  >  body text

类型转换 - 求一个高效的double转char*的算法,C或C++

伊谢尔伦伊谢尔伦2765 days ago703

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:12:43

    Is sprintf not efficient enough?
    Just take out the sprintf function about %f without using the library function.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:12:43

    If you want to omit the processing of % by sprintf, it is recommended to use the _gcvt_s function.

    How to use it:

        char buffer[320];
        _gcvt_s(buffer, 320, number, 30);
        vint len = (vint)strlen(buffer);
        if (buffer[len - 1] == '.')
        {
            buffer[len - 1] = '
    void _gcvt_s(char* buffer, size_t size, double value, vint numberOfDigits)
    {
        sprintf(buffer, "%f", value);
        char* point = strchr(buffer, '.');
        if(!point) return;
        char* zero = buffer + strlen(buffer);
        while(zero[-1] == '0')
        {
            *--zero = 'rrreee';
        }
        if(zero[-1] == '.') *--zero = 'rrreee';
    }
    
    '; }

    If the compiler you are using does not have _gcvt_s, you can encapsulate one yourself:

    rrreee

    In this way, the program can exert excellent performance under other compilation periods and under VC++.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:12:43

    Why no one mentioned the grisu algorithm. It is the fastest, "completely correct" algorithm
    Run in the library: https://github.com/night-shift/fpconv

    reply
    0
  • Cancelreply