Double decimal places for coordinates
-
01-07-2021 - |
Pregunta
I am trying to convert a string to a double value to use it as a coordinate in an annotation.
I need the double value to have 5 decimal places to be placed on the map.
Let's say the string is hello
and the double I need is whatsup
.
The format of the string is exactly the way I want it and I want to make it a double, so I use the doublevalue property of the string.
NSString *hello = @"12.61655";
double whatsup = hello.doubleValue;
NSLog(@"%f",whatsup); //this gives 12.616550 WITH A ZERO in the end
NSLog(@"%.5f",whatsup); //This gives me the correct value of 12.61655 with only 5 decimal places
So now if I want to write:
coordinate.latitude = whatsup
it gives the double with the extra zero.
How can I write
coordinate.latitude = SOMETHING HERE
which is the double with only 5 decimal places?
Can I implement the "%.5f" here somehow?
Have tried the numberformatter but it gives me an NSnumber. I need a double:
I am using this code in a for loop to plot the annotations (pins).
When i use the same forloop with doubles I hardcode it works fine. But when I use this code to get the values from the csv file, I dont get any pins:
double latitudeFromCSV = [[components objectAtIndex:0] doubleValue];
double longitudeFromCSV = [[components objectAtIndex:1] doubleValue];
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = latitudeFromCSV;
annotationCoord.longitude = longitudeFromCSV;
Solución
Check out the NSString method -stringWithFormat:
But to make it good you'll need to remove the leading zeros as you can't know there will be no value like @"12.50000".
NSNumberFormatter * nf = [[NSNumberFormatter new] autorelease];
nf.maximumFractionDigits = 5;
NSLog(@"%@", [nf stringFromNumber:[NSNumber numberWithFloat:@"12.61655f".doubleValue]]);
should give you 12.61655
as an output string.