Ios NSString stringWithFormat无法设置指数记录的精度
我试图在文本字段上显示非常小的双值。例如,doCalculationForEqualPressed函数返回0.00008,但当我在文本字段中显示它时,它会显示一条指数记录8e-05。我不需要在指数视图中显示数字。使用指数记录时如何设置精度 使用说明符%.9g-没有帮助Ios NSString stringWithFormat无法设置指数记录的精度,ios,objective-c,cocoa-touch,nsstring,Ios,Objective C,Cocoa Touch,Nsstring,我试图在文本字段上显示非常小的双值。例如,doCalculationForEqualPressed函数返回0.00008,但当我在文本字段中显示它时,它会显示一条指数记录8e-05。我不需要在指数视图中显示数字。使用指数记录时如何设置精度 使用说明符%.9g-没有帮助 double result; result = [self.brain doCalculationForEqualPressed:[self.brain operationArray]]; if (result == INFIN
double result;
result = [self.brain doCalculationForEqualPressed:[self.brain operationArray]];
if (result == INFINITY || result == -INFINITY || isnan(result)){
NSString *infinity = @"\u221E";
self.displayField.text = [NSString stringWithFormat:@"%@", infinity];
}
else
self.displayField.text = [NSString stringWithFormat:@"%.9g", result];
默认情况下,无法使用格式说明符完成此操作 您需要使用sprintf,然后自己删除后面的零
char str[50];
sprintf (str,"%.20g",num); // Make the number.
morphNumericString (str, 3);
void morphNumericString (char *s, int n) {
char *p;
int count;
p = strchr (s,'.'); // Find decimal point, if any.
if (p != NULL) {
count = n; // Adjust for more or less decimals.
while (count >= 0) { // Maximum decimals allowed.
count--;
if (*p != '\0') // If there's less than desired.
break;
p++; // Next character.
}
*p-- = '\0'; // Truncate string.
while (*p == '0') // Remove trailing zeros.
*p-- = '\0';
if (*p == '.') { // If all decimals were zeros, remove ".".
*p = '\0';
}
}
}
看到这个答案了吗
仅供参考-无限和NaN不是一回事。您不应该为NaN值显示无穷大符号。您是否尝试过%.9f?将修复无穷大和NaN,谢谢。使用%.9f将显示所有不重要的零。0.0000800000如果下次结果为0.0000008?如果我使用.f,我需要去掉最后一个有效数字后面的0。寻找另一种方式。