Jonas Ester
Jonas Ester

Reputation: 83

How to convert a String into a Float

From my textfield I get a string like 25,50.

I want to convert this string into a float. But if I use myFloat = [mytextfiel.text floatValue]; I just get 25.00.

Is there a method to get a float like 25.50?

Upvotes: 0

Views: 1146

Answers (5)

Maxthon Chan
Maxthon Chan

Reputation: 1189

Alternatively, you can use NSLocale to determine what to do and accomplish it with NSScanner in case you have no access to NSNumberFormatter:

  1. Wash off number groupers, like 1.000.000,00 -> 1000000,00
  2. Scan off non-numeric leading characters.
  3. Scan out the integral part of the number as a string.
  4. Scan off non-numeric character between the integral and fraction parts.
  5. Scan out the fraction part as a string.
  6. Reassemble a string with format @"%@.%@".
  7. Parse that reconstructed string.

This will parse out virtually any case of use, i.e. 1.500,50€ in German, 1,500€50 in French, $1500.50 in English will all result in number 1500.5

Upvotes: 1

dandan78
dandan78

Reputation: 13864

Replacing the commna with a period works, but you can also use an NSNumberFormatter and set your locale appropriately (note: untested code):

NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
formatter.locale = [NSLocale currentLocale];
formatter.localizesFormat = YES;
float myFloat = [[formatter numberFromString:string] floatValue];

Upvotes: 5

DharaParekh
DharaParekh

Reputation: 1730

try this:

float floatNo = [[@"25.50" stringByReplacingOccurrencesOfString:@"," withString:@"."] floatValue];
NSLog(@"%f",floatNo);

O/P

25.500000

Upvotes: 0

just replace the comma with a dot when you extract the float

myFloat = [[mytextfiel.text stringByReplacingOccurrencesOfString:@"," withString:@"."] floatValue];

Upvotes: 2

John Doe
John Doe

Reputation: 123

Floats must follow the decimal point format (no matter which region of the world), it means that the final product of your string must have a . instead of the comma. I suggest you replace it before storing in a database or before processing the value.

Upvotes: 0

Related Questions