getting 0.0000 when converting NSString value to float - objective-c

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.

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

changing a string to double returning one

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

floats in NSArray

I have an NSArray of floats which I did by encapsulating the floats using
[NSNumber numberWithFloat:myFloat] ;
Then I passed that array somewhere else and I need to pull those floats out of the array and perform basic arithmatic. When I try
[myArray objectAtIndex:i] ;
The compiler complains that I'm trying to perform arithmatic on a type id. It also won't let me cast to float or double.
Any ideas? This seems like it should be an easy problem. Maybe it will come to me after another cup of coffee, but some help would be appreciated. Thanks.
You can unbox the floats like this:
float f = [[myArray objectAtIndex:i] floatValue];
Unbox the float value from the NSNumber object thusly:
NSNumber *number = myArray[i];
float f = [number floatValue];
Your are converting float value to NSNumber object and adding it to NSArray.So you have to again convert NSNumber object to float value.
NSNumber *number = [yourArray objectAtIndex:0];
float f = [number floatValue];

How to convert NSString to NSInteger in iPhone application?

NSString * addString=[arrayyyy componentsJoinedByString:#","];
NSLog(#"add string is: %#",addString);// result is: 45,1
Now I want to convert above string into integer.
I have tried this:
NSInteger myInt=[addString intValue];
//NSLog(#"myInt is: %d",myInt);// result is: 45
If you expected 45.1 then there are two things wrong :
45.1 is not an integer. You would have to use floatValue to read the value.
45,1 (notice the comma) is not a valid float number. While 45,1 is valid in some locale (i.e. in french its 1 000,25 instead of 1,000.25) you would have to convert the string with an NSNumberFormatter before reading the floatValue.
.
// Can't compile and verify this right now, so please bear with me.
NSString *str = #"45,1";
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:#"fr_FR"] autorelease]; // lets say French from France
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setLocale:locale];
float value = [[formatter numberFromString:str] floatValue]; // value = 45.1
Try out NSExpression which works with mathematical symbols too (i.e. +, -, /, *):
NSNumber *numberValue = [[NSExpression expressionWithFormat:inputString] expressionValueWithObject:nil context:nil];
// do something with numberValue
From reading the question a lot, I think I may understand what you want.
The starting point seems to be:
NSLog(#"add string is: %#",addString);// result is: 45,1
And the current ending point is:
NSLog(#"myInt is: %d",myInt);// result is: 45
But it seems that you still want to print out 45,1
My guess on this is that you have an array of 2 strings [#"45",#"1"] called arrayyyy and you want to print out both values as integers. If this is so then what I think you want is:
NSInteger myInt1 = [[arrayyyy objectAtIndex:0] intValue];
NSInteger myInt2 = [[arrayyyy objectAtIndex:1] intValue];
NSLog(#"add string is: %d,%d",myInt1,myInt2);
Note This will crash horribly with an NSRangeException if there are not at least two strings in the array. So at the very least you should do:
NSInteger myInt1 = -1;
NSInteger myInt2 = -1;
if ([arrayyyy length] >0) myInt1 = [[arrayyyy objectAtIndex:0] intValue];
if ([arrayyyy length] >1) myInt2 = [[arrayyyy objectAtIndex:1] intValue];
NSLog(#"add string is: %d,%d",myInt1,myInt2);
But even this is bad as it assumes that the guard value of -1 will not be present in the actual data.

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;