Avoid trailing zeroes in printf()

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

    I search the string (starting rightmost) for the first character in the range 1 to 9 (ASCII value 49-57) then null (set to 0) each char right of it - see below:

    void stripTrailingZeros(void) { 
        //This finds the index of the rightmost ASCII char[1-9] in array
        //All elements to the left of this are nulled (=0)
        int i = 20;
        unsigned char char1 = 0; //initialised to ensure entry to condition below
    
        while ((char1 > 57) || (char1 < 49)) {
            i--;
            char1 = sprintfBuffer[i];
        }
    
        //null chars left of i
        for (int j = i; j < 20; j++) {
            sprintfBuffer[i] = 0;
        }
    }
    

提交回复
热议问题