Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

componentsSeparatedByString return wrong result

I used this code to cut the string

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

but why it return

22.225454330444336 and 113.554008483886719

like image 494
Haven Lin Avatar asked Feb 21 '23 03:02

Haven Lin


2 Answers

Because floating point numbers are not that accurate, you can get a higher accuracy by calling doubleValue instead of floatValue:

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

This is not a problem with componentsSeparatedByString:.

like image 118
MByD Avatar answered Mar 04 '23 21:03

MByD


I think there is problem in converting string into float. Try using double.

like image 26
Vignesh Avatar answered Mar 04 '23 21:03

Vignesh