Avoid trailing zeroes in printf()

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

    To get rid of the trailing zeros, you should use the "%g" format:

    float num = 1.33;
    printf("%g", num); //output: 1.33
    

    After the question was clarified a bit, that suppressing zeros is not the only thing that was asked, but limiting the output to three decimal places was required as well. I think that can't be done with sprintf format strings alone. As Pax Diablo pointed out, string manipulation would be required.

提交回复
热议问题