Unable to convert string value into float - iphone

when i convert a string value into float it takes o.oooo. here is the code.
NSString *amt=txtTotalBill.text;
NSLog(#"%#",amt);
float amount = [amt floatValue]
NSLog(#"%f",amount);
NSString *insertData=[NSString stringWithFormat:#"insert into tbl_Bills(Amount,Note,Due_On) values ('%f')",amount];
[database executeQuery:insertData];
NSLog(#"inert query: %#",insertData);
NSLog(#"value inserted");
[table reloadData];
[database close];
everytime it takes amount as 0.0000.In this code amt value is correct but that string value doesnt convert into float.

just tried some of your codeblock and it works out fine for me. The error could be in the NSString itself. Perhaps its not passing in a totally numerical number. Try using a CGFloat as well, although this shouldn't change anything.

I assume you've alreayd ensured that no non-numeric characters can make their way into the NSString thats to be converted.
Can you let us know whats the output you got for the NSLog for the string?
Could you also try setting an output format for the float? e.g. '%3.3f' will display 3 numbers each before and after the decimal point.

Check txtTotalBill.text if the text is float number format.
If text is not float number format, [NSString floatValue] retuns 0.00000

Try this, i think this will work.
float amount = [txtTotalBill.text floatValue];

This works perfect
NSString *amt = txtTotalBill.text;
float amount;
amount = [amt floatValue];

Related

iphone NSString stringWithFormat and float

I have an input with UIKeyboardTypeDecimalPad and I need my user to input a float (with unlimited characters after a dot). After the input I filter the string with :
NSString *newValue = [NSString stringWithFormat:#"%.f",[textField.text floatValue]]
But that gives me a lot of unnecessary digits after a dot (for example for 2.25 it gives 2.249999).
All I need is to filter the input so it'll be a legal float (digits and not more than one dot).
How do I do that?
NSString *newValue = [NSString stringWithFormat:#"%0.1f", [textField.text floatValue]];
the number after the dot is the number of decimal places you want.
UPDATE:
You could use string manipulation to determine the number of decimal places the user typed in (don't forget to check for edge cases):
NSInteger numberOfDecimalPlaces = textString.length - [textString rangeOfString:#"."].location - 1;
and then if you want to create a new string with a new float to the same level of display precision you could use:
NSString *stringFormat = [NSString stringWithFormat:#"%%0.%if", numberOfDecimalPlaces];
NSString *newString = [NSString stringWithFormat:stringFormat, newFloat];
Not sure if this is what you want but try something like the following:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
// set to long number of decimals to accommodate whatever a user might enter
[nf setMaximumFractionDigits:20];
NSString *s = [nf stringFromNumber:
[NSNumber numberWithDouble:[userEnteredNumberString doubleValue]]
];
NSLog(#"final:%#",s);
Try using a double instead of float. I think the double removes all trailing zero's.

Display NSNumber In Label

I am trying to display an NSNumber from an array with keys into an UILabel. Here is my current code: marblesNeeded.text = [[[records objectAtIndex:0] valueForKey: #"marblesneeded"] intValue];
I also get the error:
warning: Semantic Issue: Incompatible integer to pointer conversion assigning to 'NSString *' from 'int'
Thanks
You need to create an NSString to set the text of a UILabel.
marblesNeeded.text = [NSString stringWithFormat:#"%i",[[[records objectAtIndex:0] valueForKey: #"marblesneeded"] intValue]];
In the format %i denotes that you will be providing an integer value after the format.
Edit:
As some comments have noted NSNumber does have a stringValue, it does work but is not my personal preference because it gives you little control as to the format of the string. Consider this example.
NSNumber *number = [NSNumber numberWithFloat:3.25];
NSLog(#"%#",number.stringValue); // Will print 3.25
NSLog(#"%#",[NSString stringWithFormat:#"%i",number.intValue]); // Will print 3
Since the question envolved printing an intValue this more explicit format may be necessary.
marblesNeeded.text = [[[records objectAtIndex:0] valueForKey: #"marblesneeded"] stringValue];

How can I read Float from Core Data / iPhone?

I have Float values stored in Core-Data.
What is the code to use to read these values in an NSstring ?
Core-Data uses NSNumber objects to store the float value.
To get the 'raw' float value and put it into a string you would use something like this.
NSNumber *floatNumber = [managedObject valueForKey:#"myFloatValueKey"];
float myFloat = [floatNumber floatValue];
NSString *floatString = [NSString stringWithFormat:#"%f", myFloat];
Maybe a NSNumberFormatter would be useful.
Well, assuming that you mean your Core Data entity has an attribute of type float, you could simply access that field after you perform a fetch of that object.
[[self managedObjectContext] fetchObjectsForEntityName:#"EntityName" withPredicate:
#"(attribute LIKE[c] 'value') AND (attribute2 > %#)", someValue];
You could then put this in string format with this:
NSString* myNewString = [NSString stringWithFormat:#"%f", [[managedObject floatAttribute] floatVal]];

Problem when converting NSString to NSNumber in iPhone

I am having problem when converting string (YaxisData) to NSNumber. I have to return a NSNumber for Core-plot to get the graph done but its not working. Here's the sample code
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSNumber *num = [NSNumber numberWithDouble:[[YaxisData objectAtIndex:index] doubleValue]];
return num;
}
num returns junk data such as -1 or 993494949494 but when I log the double value of number, it prints the correct value. I am not able to return this double value as the function signature requires only the NSNumber to be returned.
NSLog(#"Number: %f", [num doubleValue]);
I am stuck here and would really appreciate any help in this regard. Thanks!
Would this give a better result somehow?
NSString *aString = [YaxisData objectAtIndex:index];
NSLog(#"%#", aString);
double value = [aString doubleValue];
NSLog(#"%f", value);
NSNumber *number = [NSNumber numberWithDouble:value];
NSLog(#"%#", number);
If not, could you show the results of the NSLog()'s?
I know that in practice it seems the same code, yet one might not be so sure that -objectAtIndex: always returns a string. It might be a localization issue as well (commas and dots for decimal separator might get mixed up, this would definitely mess up your results. In case of a localization issue, check the following link:
How to convert an NSString into an NSNumber

intValue is missing decimals

I have a price that I need to convert based on the selected currency.
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"currency.plist"];
NSDictionary *plistDictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];
int price = [price intValue];
int currencyValue = [[plistDictionary valueForKey:#"EUR"] intValue];
int convertedCurrency = (price / currencyValue);
price is an NSNumber and the valueForKey is also a number from a plist file I have setup with conversion rates.
The problem I am having, is that my price is missing the decimals. Everytime I get the intValue from the price it's just rounded up or down. The same issue exists for the exchange rate I get from the plist.
I have looked into NSNumberFormatter but it won't let me setFormat for the NSNumberFormatter. Any advice, please?
int is an integer type - by definition it does not have a decimal value. Instead try:
float fprice = [price floatValue];
float currencyValue = [[plistDictionary valueForKey:#"EUR"] floatValue];
float convertedCurrency = (fprice / currencyValue);
intValue returns an integer, which (by definition) is rounded to a number without decimals.
You could use doubleValue, which returns a double (which does have the fractional portion) or decimalValue which returns a NSDecimal object.
Take the price string and remove the period. After that convert the NSString to and int, which means you end up with 4235 pennies (or 42 dollars and 35 cents). (Also, make sure that the price string you're getting has two decimal places! Some people are lazy, and output "3.3" for "$3.30".)
NSString *removePeriod = [price stringByReplacingOccurrencesOfString:#"." withString:#""];
int convertedPrice = [removePeriod intValue];
float exchangeRate;
Then get the exchange rates depending on which currency has been selected and use the following code:
int convertedCurrency = round((double)convertedPrice / exchangeRate);
addCurrency = [NSString stringWithFormat: #"%0d.%02d", (convertedCurrency / 100), (convertedCurrency % 100)];
addCurrency is your final price.
To deal with the exact number of deciamlas and if all your currencies have 2 decimal places (e.g not JPY) make all numbers the number of cents
e.g. store 43.35 EUR as 4235.
Then you can use in arithmetic and then just deal with formatting using value/100.0 and NSNumberFormatter