【问题标题】:NSString stringWithFormat cant set precision for exponential recordNSString stringWithFormat 无法为指数记录设置精度
【发布时间】:2014-04-20 03:43:26
【问题描述】:

我试图在TextField 上显示非常小的双精度值。例如,doCalculationForEqualPressed 函数返回 0.00008,但是当我在文本字段中显示它时,它显示的是指数记录 (8e-05)。我不需要在指数视图中显示数字。使用指数记录时如何设置精度???

使用说明符 %.9g - 没有帮助。

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];

【问题讨论】:

  • 仅供参考 - 无穷大和 NaN 不是一回事。您不应该为 NaN 值显示无穷大符号。
  • 你试过%.9f吗?
  • 将修复 infinity 和 nan,谢谢。
  • 使用 %.9f 显示所有不重要的零。 (0.000080000)
  • 如果下次结果是0.0000008?如果我使用 .f 我需要去掉最后一个有效数字之后的那些 0。寻找另一种方式。

标签: ios objective-c cocoa-touch nsstring


【解决方案1】:

默认情况下不能使用格式说明符。

您需要使用 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';
        }
    }
}

看到这个答案

https://stackoverflow.com/a/277810/569497

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多