unsigned long long to double - objective-c

I am trying to convert an unsigned long long to a double, because I need the comma.
NSFileManager* fMgr = [[NSFileManager alloc] init];
NSError* pError = nil;
NSDictionary* pDict = [ fMgr attributesOfFileSystemForPath:NSHomeDirectory() error:&pError ];
//get DiskSpace
NSNumber* pNumAvail = (NSNumber*)[ pDict objectForKey:NSFileSystemSize ];
[fMgr release];
//byte to Mega byte
unsigned long long temp = [pNumAvail unsignedLongLongValue]/1000000;
//Mega byte to kilo byte
double tempD = (double)(temp/1000.0);
NSLog([NSString stringWithFormat:#"%qu", temp]); //result 63529
NSLog([NSString stringWithFormat:#"%i", tempD]); //result 1168231105
///////////////////////////////////////////////////but i want 63.529
What am I doing wrong?

You are mismatching your format specifier. You need to use a floating-point format to print a double. Try using %f instead of %i. The mismatch causes undefined behaviour.

I think your format is wrong. You should use %f : NSLog([NSString stringWithFormat:#"%f", tempD]);

Related

Objective-C, unsigned long _Nullable

I get a warning when I compile my code, and I'm not sure how to resolve it.
warning: incompatible integer to pointer conversion initializing
'unsigned long *' with an expression of type 'unsigned long
_Nullable'
NSDictionary *dict = #{#"foo": #420};
unsigned long *num = [[dict objectForKey:#"foo"] unsignedLongValue];
NSString *oct = [NSString stringWithFormat:#"%o", num];
NSLog(#"%04u", [oct intValue]); // 0644
The output is correct (I'm converting a number to octal format), but I guess my code isn't up to par with the compiler.
Two mistakes here -
1) unsigned long is not an object but primitive.
You simply need to remove the "*" before num as follow -
unsigned long num = [[dict objectForKey:#"foo"] unsignedLongValue];
2) The format of unsigned long is %lu and not %o as you mentioned.
NSString *oct = [NSString stringWithFormat:#"%lu", num];
So, the correct code should be -
NSDictionary *dict = #{#"foo": #420};
unsigned long num = [[dict objectForKey:#"foo"] unsignedLongValue];
NSString *oct = [NSString stringWithFormat:#"%lu", num];
NSLog(#"%04u", [oct intValue]); // 0644
I believe that this should work (the warnings went away):
unsigned long num = (unsigned long)[[dict objectForKey:#"foo"] unsignedLongValue];
NSString *oct = [NSString stringWithFormat:#"%lo", num];

Converting a string to double for coordinate use, Xcode

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

objective c - Xcode long int display with formatting

I’m having issues with this when the numbers are large. For example if the number is 3670000000, I want the label to be 3,670,000,000. When the numbers are large it gives me a value of 2,147,483,657. I’m sure it must be a variable length issue. I tried using long long int for numC. Any suggestions would be greatly appreciated. Thanks.
int numC;
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *valuestring= [NSString stringWithFormat:#"%#", [[values objectAtIndex:indexA] objectForKey:#"hits"]];
numC=[valuestring intValue];
NSString *results = [formatter stringFromNumber:[NSNumber numberWithInteger:numC]];
label1.text =results;
The int type cannot hold a value greater than 2,147,483,657. You could use an unsigned int and the maximum value would be 4,294,967,295. Look here for more information. You could try this too to extend the range of the data type:
long long int numC;
//Number formatter and string operations
numC = [valuestring longLongValue];
NSString *results = [formatter stringFromNumber:[NSNumber numberWithLongLong: numC]];
label1.text = results;
Additionally, if none of the values you are retrieving contain a negative value, you could make it an unsigned long long int. In that case, make your code this:
unsigned long long int numC;
//Number formatter and string operations
numC = [valuestring longLongValue];
NSString *results = [formatter stringFromNumber:[NSNumber numberWithUnsignedLongLong: numC]];
label1.text = results;
Also make sure that in this line...
NSString *valuestring= [NSString stringWithFormat:#"%#", [[values objectAtIndex:indexA] objectForKey:#"hits"]];
...the value you are retrieving is a long long int.
Hope this helps!
There is also the C++ class for bigInteger if you really need to do operations with numbers larger than allowed by int. If you don't need to do many operations, store the number as a NSString. Then to work with it just take the end of the string, convert it to an int, do your operations, then put the number back into the string.

Pull serverOutputValue as NSInteger

Ho Everybody I aam trying to call php script thorugh my iphone application that return me a integer value as serverOutput
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSInteger * userid = [serverOutput integerValue];
NSLog(#" %d" , userid);
But if my print my serverOutput string it is 2381164503 but my NSLog(#" %d" , userid) prints me 2147483647. I dont know for some reason it is parsing different value :(
First, NSInteger is a primitive type so you shouldn't declare userid as a pointer (by putting the asterisk in front). Second, the value 2381164503 is too big for an NSInteger (max is 2147483647).
Try using a long long instead:
long long userid = [serverOutput longLongValue];
NSLog(#" %lld" , userid); //use %lld instead of %d

Using NSLog for debugging

I have the following code snippet in my Xcode:
NSString *digit [[sender titlelabel] text];
NSLog([digit]);
I tried to build the application and am getting the following warning message for the line NSLog([digit]);
Warning: Format not a string literal and no format arguments
Can you advise me how I can resolve this warning message? What does the message actually mean?
Try this piece of code:
NSString *digit = [[sender titlelabel] text];
NSLog(#"%#", digit);
The message means that you have incorrect syntax for using the digit variable. If you're not sending it any message - you don't need any brackets.
Use NSLog() like this:
NSLog(#"The code runs through here!");
Or like this - with placeholders:
float aFloat = 5.34245;
NSLog(#"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat);
In NSLog() you can use it like + (id)stringWithFormat:(NSString *)format, ...
float aFloat = 5.34245;
NSString *aString = [NSString stringWithFormat:#"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat];
You can add other placeholders, too:
float aFloat = 5.34245;
int aInteger = 3;
NSString *aString = #"A string";
NSLog(#"This is my float: %f \n\nAnd here is my integer: %i \n\nAnd finally my string: %#", aFloat, aInteger, aString);
Why do you have the brackets around digit?
It should be
NSLog("%#", digit);
You're also missing an = in the first line...
NSString *digit = [[sender titlelabel] text];
The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:
Instead of:
NSString *digit = [[sender titlelabel] text];
NSLog(digit);
Use:
NSString *digit = [[sender titlelabel] text];
NSLog(#"%#",digit);
It will still work doing that first way, but doing it this way will get rid of the warning.
type : BOOL
DATA (YES/NO) OR(1/0)
BOOL dtBool = 0;
OR
BOOL dtBool = NO;
NSLog(dtBool ? #"Yes" : #"No");
OUTPUT : NO
type : Long
long aLong = 2015;
NSLog(#"Display Long: %ld”, aLong);
OUTPUT : Display Long: 2015
long long veryLong = 20152015;
NSLog(#"Display very Long: %lld", veryLong);
OUTPUT : Display very Long: 20152015
type : String
NSString *aString = #"A string";
NSLog(#"Display string: %#", aString);
OUTPUT : Display String: a String
type : Float
float aFloat = 5.34245;
NSLog(#"Display Float: %F", aFloat);
OUTPUT : isplay Float: 5.342450
type : Integer
int aInteger = 3;
NSLog(#"Display Integer: %i", aInteger);
OUTPUT : Display Integer: 3
NSLog(#"\nDisplay String: %# \n\n Display Float: %f \n\n Display Integer: %i", aString, aFloat, aInteger);
OUTPUT :
String: a String
Display Float: 5.342450
Display Integer: 3
http://luterr.blogspot.sg/2015/04/example-code-nslog-console-commands-to.html
NSLog(#"%#", digit);
what is shown in console?
NSLog([digit]); // [] are the messages in Objective-C, just like methods or functions in other programming languages
Since you just need to print the value of 'digit'
Either you can call -
NSLog(digit); // A warning would occur - Format string is not a string literal (potentially insecure)
OR
NSLog(#"%#",digit]); // But if you use %# to reference the object, the warning will go away.
Both the methods will work but the second one is the right way of logging to console.