How to prevent the rounding off when getting doubleValue from string?

为君一笑 提交于 2019-12-02 15:52:46

问题


I am getting latitude and longitude from server in JSON which is in string format then i am using this latitude and longitude by converting the values of latitude and longitude in double value by using default doubleValue function but by using this value is rounded off. So, How can i prevent the rounding off when getting doubleValue from string? Here is my code

  CLLocationCoordinate2D defaultLoc;

            defaultLoc.latitude = [[self.obj valueForKey:@"latitude"] doubleValue];
            defaultLoc.longitude = [[self.obj valueForKey:@"longitude"] doubleValue]; 

            NSLog(@"latitude : %f longitude : %f",defaultLoc.latitude,defaultLoc.longitude);

回答1:


The format specifier %f rounds the double values to six decimals by default. Try specifing the format as %.10for whatever number of decimals you need.




回答2:


The same problem i had. I solved it by , having the lat long data from JSON as NSString. Create an object class to hold the NSString equivalent of your lat and long

 NSString * lattodeletetest;
 NSString * longtodeletetest;
 lattodeletetest=[dict objectForKey:@"Lat"];
 longtodeletetest=[dict objectForKey:@"Lon"];
 NSArray *array2=[[NSArray alloc] initWithObjects:lattodeletetest,longtodeletetest, nil];
 NSString * coordinateString2=[array2 componentsJoinedByString:@","];
 safe.strLatLong=coordinateString2;

NSLog(@"%@",safe.strLatLong); //prints 12.758493847753464,71.488293492438438

By this way it is possible to preserve the lat and long obtained from JSON without edits.

To use it as CLLOcationCoordinate2d , use

 NSString *str=strLatLong;
 NSArray *array=[str componentsSeparatedByString:@","];
 lattodeletetest=[array objectAtIndex:0];
 longtodeletetest=[array objectAtIndex:1];
 CLLocationCoordinate2D location=CLLocationCoordinate2DMake([lattodeletetest doubleValue],[longtodeletetest doubleValue]);


来源:https://stackoverflow.com/questions/11189464/how-to-prevent-the-rounding-off-when-getting-doublevalue-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!