我有一个 Objective-C 项目需要显示像 0.00000217 这样的数字,以及非常小的数字。问题是,Objective-C 将其四舍五入到小数点后 6 位,因此它显示为 0.000002。有没有显示更多小数位的类型?我的代码:
float floatValueOfSmallNumber = [value floatValue];
[theLabel setText:[NSString stringWithFormat:@"%f", floatValueOfSmallNumber]];
谢谢!
虽然 float
只有大约 7 位有效的小数位,但这不是您在这里遇到的问题;毕竟,0.00000217
只有三位有效数字。
您正在使用从 C 继承并定义的 %f
格式说明符(7.21.6 格式化输入/输出函数):
A double argument representing a floating-point number is converted to decimal notation in the style [−]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is zero and the # flag is not specified, no decimal-point character appears. If a decimal-point character appears, at least one digit appears before it. The value is rounded to the appropriate number of digits.
使用 double
不会改变这个;相反,您需要更改格式说明符。如果您不介意科学记数法,可以使用 %e
或 %g
,但另一种选择是使用精度说明符:%.10f
,例如,将打印十位十进制数字。