How to use “%f” to populate a double value into a string with the right precision

时光总嘲笑我的痴心妄想 提交于 2019-12-10 13:25:23

问题


I am trying to populate a string with a double value using a sprintf like this:

sprintf(S, "%f", val);

But the precision is being cut off to six decimal places. I need about 10 decimal places for the precision.

How can that be achieved?


回答1:


%[width].[precision]

Width should include the decimal point.

%8.2 means 8 characters wide; 5 digits before the point and 2 after. One character is reserved for the point.

5 + 1 + 2 = 8




回答2:


What you want is a modifier:

sprintf(S, "%.10f", val);

man sprintf will have many more details on format specifiers.




回答3:


For a more complete reference, see the Wikipedia printf article, section "printf format placeholders" and a good example on the same page.




回答4:


Take care - the output of sprintf will vary via C locale. This may or may not be what you want. See LC_NUMERIC in the locale docs/man pages.




回答5:


%f is for float values.

Try using %lf instead. It is designed for doubles (which used to be called long floats).

double x = 3.14159265;
printf("15.10lf\n", x);



来源:https://stackoverflow.com/questions/69743/how-to-use-f-to-populate-a-double-value-into-a-string-with-the-right-precisio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!