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];
Related
I'm looking to convert a simple objectiveC class (not even that at the minute its just some vars in a function) to JSON so that it can be sent and impretated into a java object at the server side.
The Class might have the following fields;
LatLng locationA // a simple POJO with either float or long to represent lat and long.
LatLng locationA
float someFloat
It the minute I am tring to pack everything in to a NSDictonary. Passing the floats in didn't work so I has to convert them to NSStrings. So on the server side they would arive as strings.. which isnt ideal.
CLLocationCoordinate2D location = ... ;
float lat = location.latitude;
float lng = location.longitude;
float aFloat = 0.12434f;
NSString *aFloatstr = [NSString stringWithFormat:#"%f", aFloat];
NSString *latStr = [NSString stringWithFormat:#"%f", lat];
NSString *lngStr = [NSString stringWithFormat:#"%f", lng];
NSDictionary *locationDictionary =
[NSDictionary dictionaryWithObjectsAndKeys:
latStr , #"latitude",
lngStr, #"longitude",
nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
locationDictionary, #"locationA",
locationDictionary, #"locationB",
aFloatstr,#"aFloat",
nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#",str);
Whats the best way do putting CLLocationCoordinate2Ds into an NSDictionary?
How do I add primitative types, long floats ect.. to an NSDictionary?
Instead of putting the latitude and longitude into NSString, you'll have better luck with NSNumber. When NSJSONSerialization comes upon an NSNumber it won't quote the value like it would a string (which is what you want when transmitting numbers, right?).
You'll also want to use double, not float, for latitude and longitude, since that's how they're represented internally. No need to throw away precision.
[NSNumber numberWithDouble:lat]
[NSNumber numberWithDouble:lng]
[NSNumber numberWithFloat:aFloat]
Since instances of NSNumber are objects, you'll be able to store them in NSDictionary no problem.
Use NSNumber instead of strings to wrap the float values, e.g.:
NSDictionary *locationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:lat] , #"latitude",
[NSNumber numberWithFloat:lng], #"longitude", nil];
That way, NSJSONSerialization will correctly encode them as numeric values.
Structs
Neat way of doing this is to create category for NSValue that understands your struct. In your case it's CLLocationCoordinate2D, but could be any really. Here is snippet from Apple's own documentation explaning usage of NSValue:
// NSValue+Polyhedron.h
typedef struct {
int numFaces;
float radius;
} Polyhedron;
#interface NSValue (Polyhedron)
+ (instancetype)valueWithPolyhedron:(Polyhedron)value;
#property (readonly) Polyhedron polyhedronValue;
#end
// NSValue+Polyhedron.m
#implementation NSValue (Polyhedron)
+ (instancetype)valueWithPolyhedron:(Polyhedron)value
{
return [self valueWithBytes:&value objCType:#encode(Polyhedron)];
}
- (Polyhedron) polyhedronValue
{
Polyhedron value;
[self getValue:&value];
return value;
}
#end
From here usage is quite trivial. To create boxed NSValue:
NSValue *boxedPolyhedron = [NSValue valueWithPolyhedron:yourStruct];
Now you can put boxedPolyhedron whenever NSValue can go, NSArray, NSDictionary, NSSet, and many more, plus al the mutable versions.
To get struct back:
Polyhedron polyStruct = [boxedPolyhedron polyhedronValue];
That's it.
As a bonus, this works for any C type, not only for structs.
floats, longs, etc.
As mentioned above, could do same as above. But, for numbers, you could use NSNumber which is actually a subclass if NSValue with all popular methods already implemented. Here is a list of types you can box by instantiating NSNumber:
+ (NSNumber *)numberWithChar:(char)value;
+ (NSNumber *)numberWithUnsignedChar:(unsigned char)value;
+ (NSNumber *)numberWithShort:(short)value;
+ (NSNumber *)numberWithUnsignedShort:(unsigned short)value;
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithUnsignedInt:(unsigned int)value;
+ (NSNumber *)numberWithLong:(long)value;
+ (NSNumber *)numberWithUnsignedLong:(unsigned long)value;
+ (NSNumber *)numberWithLongLong:(long long)value;
+ (NSNumber *)numberWithUnsignedLongLong:(unsigned long long)value;
+ (NSNumber *)numberWithFloat:(float)value;
+ (NSNumber *)numberWithDouble:(double)value;
+ (NSNumber *)numberWithBool:(BOOL)value;
+ (NSNumber *)numberWithInteger:(NSInteger)value;
+ (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value;
In similiar fashion you un-box values using [yourNumber longValue], [yourNumber floatValue], etc.
Hope that helps.
I have stored a value 1/129600.0 in a plist as a string.
I am able to retrieve it as a string but when i am trying to convert it as a double i am getting it as 1.0.I have also tried CFString
NSString *value = [[self array]objectAtIndex:m];
double a = [value doubleValue];
NSLog(#"%#",value);
NSLog(#"%f",a);
and in log the returned values are
1/129600.0 and 1.0
This code works fine, I tried it in xCode:
NSString *equation = [[self array]objectAtIndex:m];
NSExpression *result = [NSExpression expressionWithFormat:equation];
NSNumber *a = [result expressionValueWithObject:nil context: nil];
NSLog(#"%#",result);
NSLog(#"%.10f",[a doubleValue]);
I guess 1/129600.0 is not a valid number.
Try to create an expression and create an NSNumber from it:
NSString *equation = [[self array]objectAtIndex:m];
NSNumber *a = [[NSExpression expressionWithFormat:equation] expressionValueWithObject:nil context:nil];
double a = [result doubleValue];
NSLog(#"%f", a);
1/129600.0 is not a valid representation for a number in most programming languages, including ObjC. You need to parse the string and interpret it yourself.
Try this
NSString *value = [[self array]objectAtIndex:m];
NSArray *arr = [value componentsSeparatedByString:#"/"];
double a;
if ([arr count] == 2)
{
a = [arr objectAtIndex:0]/[arr objectAtIndex:1];
}
NSLog(#"%#",value);
NSLog(#"%f",a);
In my application, i tried to convert NSString value to float using
NSString *value = [dict objectForKey:#"student_Percentage"];
float f = [value floatValue];
But I'm getting the value of f as 0.00000. I tried with NSNumberFormatter, NSNumber... but still get 0.00000.
floatValue returns 0.0 if the receiver doesn’t begin with a valid
text representation of a floating-point number.
[dict objectForKey:#"student_Percentage"] value should be like 8.9.
Remove double quotes from your string.
NSMutableString *value = [dict objectForKey:#"student_Percentage"];
[value replaceOccurrencesOfString:#"\"" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [value length])];
float f = [value floatValue];
Hey i think your dict value has a problem. Try this code it gives the correct value.
NSString *temp = #"25.38";
float p = [temp floatValue];
NSLog(#"%f",p);
Or maybe use valueforkey instead of objectForKey.
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);
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;