Avoid trailing zeroes in printf()

前端 未结 14 2378
猫巷女王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:33

    Some of the highly voted solutions suggest the %g conversion specifier of printf. This is wrong because there are cases where %g will produce scientific notation. Other solutions use math to print the desired number of decimal digits.

    I think the easiest solution is to use sprintf with the %f conversion specifier and to manually remove trailing zeros and possibly a decimal point from the result. Here's a C99 solution:

    #include 
    #include 
    
    char*
    format_double(double d) {
        int size = snprintf(NULL, 0, "%.3f", d);
        char *str = malloc(size + 1);
        snprintf(str, size + 1, "%.3f", d);
    
        for (int i = size - 1, end = size; i >= 0; i--) {
            if (str[i] == '0') {
                if (end == i + 1) {
                    end = i;
                }
            }
            else if (str[i] == '.') {
                if (end == i + 1) {
                    end = i;
                }
                str[end] = '\0';
                break;
            }
        }
    
        return str;
    }
    

    Note that the characters used for digits and the decimal separator depend on the current locale. The code above assumes a C or US English locale.

提交回复
热议问题