iphone – componentsSeparatedByString返回错误的结果

前端之家收集整理的这篇文章主要介绍了iphone – componentsSeparatedByString返回错误的结果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用这段代码来剪切字符串

NSString *titleString = @"22.225453615805794,113.554006577014889";
    NSArray *array = [titleString componentsSeparatedByString:@","];
    NSLog(@"title string %@",titleString);
    NSLog(@"first %.15f",[[array objectAtIndex:0] floatValue]);
    NSLog(@"second %.15f",[[array objectAtIndex:1] floatValue]);

但为什么它会回来

22.225454330444336

113.554008483886719

解决方法

因为浮点数不准确,所以通过调用doubleValue而不是floatValue可以获得更高的精度:

NSLog(@"second %.15f",[[array objectAtIndex:1] doubleValue]);

这与componentsSeparatedByString:不是问题.

猜你在找的Xcode相关文章