Building string with float variables - objective-c

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

Related

How to operate with float stored in dictionary in objective-c?

I have NSDictionary *results
When i do this:
self.tValue.text = [NSString stringWithFormat:#"%#", [results objectForKey:#"temperature"] + 273.15f];
I get the error:
Invalid operands for binary expression ('id _Nullable' and 'float')
Where I wrong?
The "float" stored in the NSDictionary is likely to be an NSNumber (or possibly an NSString) - it can't actually be a "float". You therefore need to get the "floatValue" of your NSDictionary value, do your addition, and then use the "float" string format.
Try the following:
self.tValue.text = [NSString stringWithFormat:#"%f", [results[#"temperature"] floatValue] + 273.15f];
you are adding float value with id object before doing that you must have convert temperature value into float Like:
CGFloat temperature = [[results objectForKey:#"temperature"] floatValue];
NSString *tValue = [NSString stringWithFormat:#"%f", temperature + 273.15f];

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

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 ASCII decimal integer to NSString conversion

How can I convert and ASCII decimal integer to an NSString in Objective-C? (Example: 36 to "$")
Thanks
Try this:
unichar asciiChar = 36;
NSString *stringWithAsciiChar = [NSString stringWithCharacters:&asciiChar length:1];
You can use the following:
NSString *s = [NSString stringWithFormat:#"%c", 36];
NSLog(#"%#", s); // $

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;