Search code examples
iosiphone-sdk-3.0ios-4.2ios4

Converting String to float in ios


Hello friends I Have a float type variable ,which contains a total price of specific item,so first I have converted into NSString..below is my code

float total;

[grandTotal setText:[NSString stringWithFormat:**@"$%.2f"**,total]];

so here grandTotal is of type UILabel..where I want the total in the format which I have written in the code

now again when i try to covert to do this

float previousTotal = [[grandTotal text] floatValue];

I am getting value of previousTotal = zero.

So I think their is issue with $ sign how to solve this is issue..


Solution

  • In your case you can solve it by using

    float previousTotal = [[[grandTotal text] stringByReplacingOccurrencesOfString:@"$" withString:@""] floatValue];
    

    But I think it is better to pass directly your float value.