Avoid trailing zeroes in printf()

前端 未结 14 2348
猫巷女王i
猫巷女王i 2020-11-22 07:18

I keep stumbling on the format specifiers for the printf() family of functions. What I want is to be able to print a double (or float) with a maximum given number of digits

14条回答
  •  無奈伤痛
    2020-11-22 07:49

    Hit the same issue, double precision is 15 decimal, and float precision is 6 decimal, so I wrote to 2 functions for them separately

    #include 
    #include 
    #include 
    #include 
    
    std::string doublecompactstring(double d)
    {
        char buf[128] = {0};
        if (isnan(d))
            return "NAN";
        sprintf(buf, "%.15f", d);
        // try to remove the trailing zeros
        size_t ccLen = strlen(buf);
        for(int i=(int)(ccLen -1);i>=0;i--)
        {
            if (buf[i] == '0')
                buf[i] = '\0';
            else
                break;
        }
    
        return buf;
    }
    
    std::string floatcompactstring(float d)
    {
        char buf[128] = {0};
        if (isnan(d))
            return "NAN";
        sprintf(buf, "%.6f", d);
        // try to remove the trailing zeros
        size_t ccLen = strlen(buf);
        for(int i=(int)(ccLen -1);i>=0;i--)
        {
            if (buf[i] == '0')
                buf[i] = '\0';
            else
                break;
        }
    
        return buf;
    }
    
    int main(int argc, const char* argv[])
    {
        double a = 0.000000000000001;
        float  b = 0.000001f;
    
        printf("a: %s\n", doublecompactstring(a).c_str());
        printf("b: %s\n", floatcompactstring(b).c_str());
        return 0;
    }
    

    output is

    a: 0.000000000000001
    b: 0.000001
    

提交回复
热议问题