Avoid trailing zeroes in printf()

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

    Your code rounds to three decimal places due to the ".3" before the f

    printf("%1.3f", 359.01335);
    printf("%1.3f", 359.00999);
    

    Thus if you the second line rounded to two decimal places, you should change it to this:

    printf("%1.3f", 359.01335);
    printf("%1.2f", 359.00999);
    

    That code will output your desired results:

    359.013
    359.01
    

    *Note this is assuming you already have it printing on separate lines, if not then the following will prevent it from printing on the same line:

    printf("%1.3f\n", 359.01335);
    printf("%1.2f\n", 359.00999);
    

    The Following program source code was my test for this answer

    #include 
    
    int main()
    {
    
        printf("%1.3f\n", 359.01335);
        printf("%1.2f\n", 359.00999);
    
        while (true){}
    
        return 0;
    
    }
    

提交回复
热议问题