我如何创建一个字符串,以便它格式化 float ,当它是整数时没有尾随小数点或数字,但对于更大的数字不切换为科学记数法?
当我这样做时:
float myFloat= 15.6f;
float myInt = 5.0f;
float myLarge = 7000000.0f;
sprintf(out, "my float is %g", myFloat);
sprintf(out, "my int is %g", myInt);
sprintf(out, "my large is %g", myLarge);
我得到类似的东西:
my float is 15.6 my int is 5 my large is 7e+07f
I want all a single format string that will give 15.6, 5, and 700000.
Edited cause comments don't do formatting:
that's what I thought. but a wrapper is pretty inconvenient though as the format strings are embedded in longer format strings:
sprintf(buf, "%d %g", myInt, myFloat);
你是怎么包装的?
sprintf(buf, "%d %g", myInt, Wrapper(myFloat));??
Wrapper 应该返回什么?或者更糟:
sprintf(buf, "%d %s", myInt, Wrapper(myFloat));??
最佳答案
您可以使用“%.*f”进行格式化,这允许您将精度作为单独的参数传递给例如sprintf.过去,当我想很好地显示 0、1、2 或 3 位数字而没有额外的尾随 0 时,我曾使用过它。编写一个小辅助函数,它采用 double / float 并返回整数精度(通过乘以 1000,然后对 10、100、1000 取模)。然后用"%.*f"调用sprintf,调用辅助函数,并传递float。
关于c - C 中带有 %g 的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/827499/