代码之家  ›  专栏  ›  技术社区  ›  Omkar Jadhav

将NSString转换为double进行计算,然后再返回以在NSString中打印

  •  12
  • Omkar Jadhav  · 技术社区  · 15 年前

    我接受NSString作为

    NSString *value = [valuelist objectAtIndex:valuerow];
    NSString *value2 = [valuelist2 objectAtIndex:valuerow2];
    

    我想

    double *cal = value + (value2 * 8) + 3;
    
    
    NSString *message =[[NSString alloc] initWithFormat:@"%@",cal];
    

    我应该可以在计算完字符串后得到它。。请帮忙 我的程序崩溃了

    4 回复  |  直到 15 年前
        1
  •  35
  •   Joshua Weinberg    15 年前
    double cal = [value doubleValue] + ([value2 doubleValue] * 8) + 3;
    NSString *message =[[NSString alloc] initWithFormat:@"%f",cal];
    
        2
  •  3
  •   tc.    15 年前

    你不应该一直在双精度和字符串之间转换,因为它会失去准确性(一般来说,你必须这样做) 非常小心 如果你不想失去准确性)。

    例如, nextafter(1.0,2.0)

    我们希望NSNumber做正确的事,但是 [[NSNumber numberWithDouble:nextafter(1,2)] stringValue] 同时返回“1”。根据文件, -[NSNumber stringValue] [self descriptionWithLocale:nil] 将其格式化为“%0.16g”。这还不够。不过,我们通过用“%.17g”格式化得到正确答案。我认为只要double是ieee754 64位double并且库工作正常,“%.17g”就足够了,但是不能保证。

    归根结底,这并不能保证 [[NSString stringWithFormat:@"%.17g",n] doubleValue] == n

        3
  •  1
  •   taskinoor    15 年前
    NSString*message=[[NSString alloc]initWithFormat:@“%g”,cal];
    
    //处理消息
    
    [信息发布];
    
        4
  •  1
  •   TooTone    11 年前

    发布一个新答案,因为接受的答案只执行string=>双倍:

    double cal = [value doubleValue] + ([value2 doubleValue] * 8) + 3;
    NSString *message =[[NSString alloc] initWithFormat:@"%f",cal];
    

    加倍=>字符串,使用

    double cost = [string doubleValue];