Developer
Developer

Reputation: 1435

Unable to convert string value into float

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.

Upvotes: 0

Views: 825

Answers (5)

user2998756
user2998756

Reputation: 71

This works perfect

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

Upvotes: 0

Mobile App Dev
Mobile App Dev

Reputation: 1814

Try this, i think this will work.

float amount = [txtTotalBill.text floatValue];

Upvotes: 0

ePerera
ePerera

Reputation: 56

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.

Upvotes: 2

ChangUZ
ChangUZ

Reputation: 5438

Check txtTotalBill.text if the text is float number format.

If text is not float number format, [NSString floatValue] retuns 0.00000

Upvotes: 1

Madhu
Madhu

Reputation: 2384

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.

Upvotes: 2

Related Questions