Converting a string to double for coordinate use, Xcode - objective-c

I have a list of longitudes and latitudes in an XML file. I can print the lat and lon as a string but when i convert the string to a double i get 0.
Here is my code:
NSString *latstring = [[NSString alloc] initWithString:theList.lat] ;
NSString *lonstring = [[NSString alloc] initWithString:theList.lon];
NSLog(#"latstring: %#, lonstring: %#", latstring, lonstring);
double latdouble = [latstring doubleValue];
double londouble = [lonstring doubleValue];
NSLog(#"latdouble: %g, londouble: %g", latdouble, londouble);
When i log 'latstring' and 'lonstring' i get the correct coordinates however when i log 'latdouble' and 'londouble' i get 0.
I need the lat and lon values as double so i can use them in a mapview as it will not allow me to use a string for the coordinates.
There is probably a very simple explanation for this however i am fairly new to objective-c and cant seem to find a solution for this.
Any help is much appreciated.

Solved the issue. After counting the length of the strings like Phillip said to do it turned out the length was 1 character longer than the string. So i added another string in-between that was the same string as 'latstring' and 'lonstring' however it began at index 1 rather than 0, therefore cutting off whatever character must have been infront of the coordinate value. This then converted to double perfectly.
Here is the code is used:
NSString *latstring = theList.lat;
NSString *lonstring = theList.lon;
NSLog(#"%#, %# wooo", latstring, lonstring);
NSString *latcutstring = [latstring substringFromIndex:1];
NSLog(#"cut lat: %#", latcutstring);
NSString *loncutstring = [lonstring substringFromIndex:1];
NSLog(#"cut lon: %#", loncutstring);
double latdouble = [latcutstring doubleValue];
NSLog(#"latdouble: %f", latdouble);
double londouble = [loncutstring doubleValue];
NSLog(#"londouble: %f", londouble);
Thankyou Phillip Mills and Tobol for you're help.
EDIT: Nov 2012
It was white space causing problems and i have found a safer way of doing this as to not cut out needed characters, as craig and phillip said.
NSString *trimlat = [theList.lat stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *trimlon = [theList.lon stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//Convert to double
double latdouble = [trimlat doubleValue];
double londouble = [trimlon doubleValue];
//Create coordinate
CLLocationCoordinate2D coord = {(latdouble),(londouble)};

I think those strings aren't formatter well. there can't be anything else than whitespace before the number. The lat and lon has to be in format like as 'dd.ddddddd'.
NSString *works = #" 12.5431 jdty";
NSString *doesntWorks = #"E 43.4345";
NSString *latstring = [[NSString alloc] initWithString:works] ;
NSString *lonstring = [[NSString alloc] initWithString:doesntWorks];
NSLog(#"latstring: %#, lonstring: %#", latstring, lonstring);
double latdouble = [latstring doubleValue];
double londouble = [lonstring doubleValue];
NSLog(#"latdouble: %g, londouble: %g", latdouble, londouble);

Related

Objective-C: Double to NSString with x-many decimals

I know that I can cast a double to a NSString with a specific amount of decimals like so:
double myDouble = 123.456789;
NSString *myString = [NSString stringWithFormat:#"%.4g", myDouble];
But how can I replace the number "4" in this example with a int variable?
Something like this doesn't work:
double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.%dg", myDouble, precision];
Consider using NSNumberFormatter:
double myDouble = 123.456789;
int precision = 4;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.minimumFractionDigits = precision;
formatter.maximumFractionDigits = precision;
NSString *myString = [formatter stringFromNumber:#(myDouble)];
Or, if you want this in scientific notation, you can alternatively specify something like:
formatter.numberStyle = NSNumberFormatterScientificStyle;
formatter.usesSignificantDigits = YES;
formatter.minimumSignificantDigits = precision;
formatter.maximumSignificantDigits = precision;
It just depends upon what precisely you're looking for.
This also has the virtue of also honoring the user's regional settings (e.g. if in Germany, the decimal separator is a comma, not a period).
If you need to force the locale setting (e.g. this is for creating something that will be exchanged with a web service that expects the data in a specified format), you can set the formatter's locale (e.g. [NSLocale localeWithLocaleIdentifier:#"en_US"]). But when presenting results in the user interface, you always want to honor the device's locale settings.
You can use asterisk in place of optional width and precision specifiers. And set them as arguments
double myDouble = 123.456789;
int width = 10;
int precision = 6;
NSString *s = [NSString stringWithFormat:#"%*.*g", width, precision, myDouble];
If you follow the links in the documentation for stringWithFormat you will discover the IEEE printf specification which describes the formats supported. That tells you that a field width or precision can be an * to indicate the actual value is supplied an an int argument, so what you want is:
NSString *myString = [NSString stringWithFormat:#"%.*g", intPrecision, myDouble];
double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.*f", precision, myDouble];
NSLog(#"myString: '%#'", myString);
NSLog output:
myString: '123.4567'
This is by no means an optimal way of doing it, but it is a way.
You can do it in multiple steps
NSString *val = [NSString stringWithFormat: #"%d", 4];
NSString *head = [#"%." stringByAppendingString: val];
NSString *format = [head stringByAppendingString: #"g"];
NSString *result = [NSString stringWithFormat: format, 123.456789];
Or if you're really adventurous (for the sake of readability, don't EVER do this):
NSString *result = [NSString stringWithFormat: [[#"%." stringByAppendingString: [NSString stringWithFormat: #"%d", 4]] stringByAppendingString: #"g"], 123.456789];

How to display leading zero in double

I need to make NSNumber to display only 4 decimal points. This part of code is works, but it outputs result without leading zero.
double resultRoundToDecimal = [result doubleValue];
NSNumberFormatter *resultFormatter = [[NSNumberFormatter alloc] init];
[resultFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[resultFormatter setMaximumFractionDigits:4];
resultData = [resultFormatter stringFromNumber:[NSNumber numberWithDouble:resultRoundToDecimal]];
For example:
1/3 = .3333
I want:
1/3 = 0.3333
How I can to do this?
You could choose to use string formatter too, like below
float val=1./3;
NSString *resultData=[NSString stringWithFormat:#"%0.4f",val];
NSLog(#"Result = %#",resultData);
Prepend a 0 or use number formatter.
NSString *printStr = #"0";
printStr = [NSString stringByAppendingString: resultData];
Otherwise, you could use a number formatter or something similar. If your just outputting a string why not do that?
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html

How to format the final results digit of the calculations in Objective-C?

I have this code:
double s = [year.text doubleValue]*31536000;
second.text=[[NSString alloc] initWithFormat:#"%2g", s];
When I try to calculate the final result is 3.1536e+07
How do I make the result 31536000 without e+07?
The %g and %G conversions print the argument in the style of %e or %E (respectively) if the exponent would be less than -4 or greater than or equal to the precision; otherwise they use the %f style.
You should use %f.
double s = [year.text doubleValue]*31536000;
second.text=[[NSString alloc] initWithFormat:#"%f", s];
Simple use %f.
NSString *str = [[NSString alloc] initWithFormat:#"%f", s];
second.text = str;
The second may result the string without the "e+07"
The f is because we're working w/ floating point numbers.
You should try:
double s = [year.text doubleValue]*31536000;
second.text=[[NSString alloc] initWithFormat:#"%lf", s];

Building string with float variables

How can i build a NSString variable consisting of string and float variables?
I assume i need to cast the floats to strings, but i cant see how this is done without creating alot of messy and ugly code.
I want to build something like this: String+ Float+ String+ Float
Thanks in advance.
That is not how Objective C works. In Java, you would use:
String yourString = string1 + " " + float1 + " " + string2 + " " + float2;
You cannot do the same in Objective C. To do something to the same effect, you would need:
NSString* yourString = [NSString stringWithFormat:#"%# %f %# %f", string1, float1, string2, float2];
This would result in the equivalent to the Java statement. %# indicates you want to format an object into the string, and %f indicates a floating point value.
When formatting floats in an NSString, you can specify how many decimal places you want to truncate to by placing a value in between the % and f. For example, to round the first float to 2 decimal places and the second one to 5 decimal places:
NSString* yourString = [NSString stringWithFormat:#"%# %.2f %# %.5f", string1, float1, string2, float2];
Try:
NSString *str = [NSString stringWithFormat:#"Some text %f some more text %f", floatVar, anotherFloat];
To answer the question as asked:
Assume:
NSString *str1 = #"string one";
NSString *str2 = #"string two";
float f1 = 1.0;
float f2 = 2.0;
NSString *answer = [NSString stringWithFormat:#"%#: %f. %#: %f.", str1, f1, str2, f2];
NSLog(#"%#", answer); // This will print "string one: 1.000000. string two: 2.000000."
float sampleFloatVariable = 50.0;
NSString *floatintoText = [NSString stringwithFormat:#"%f",sampleFloatVariable];
NSLog(#" float text %#",floatintoText);

Convert float value to NSString

Do you know how can i convert float value to nsstring value because with my code, there is an error.
My Code :
- (float)percent:(float)a :(float)b{
return a / b * 100;
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
// ....
float tx_nb_demande_portabilite = [self percent: [(NSNumber*) [stat nb_demande_portabilite] floatValue] :[(NSNumber*) [stat nb_users] floatValue]];
NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
//....
}
The error :
EXC_BAD ACCESS for NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
Thank you for your help.
You need to use %f format specifier for float, not %#.
NSString *str = [NSString stringWithFormat:#"%f", myFloat];
To use specific number of digits after decimal use %.nf where n is number of digits after decimal point.
// 3 digits after decimal point
NSString *str = [NSString stringWithFormat:#"%.3f", myFloat];
Obj-C uses C printf style formatting. Please check printf man page for all other possible formatting.
one more option:
NSString * str = [NSNumber numberWithFloat:value].stringValue;
#"%f" sounds like more appropriate format string for float.
[NSString stringWithFormat:#"%f", tx_nb_demande_portabilite];
A modern (and less verbose) approach would be:
NSString *str = #(myFloat).description;