some_id
some_id

Reputation: 29886

NSString to float value incorrect

I have an NSString converting to a float value and the result logged is this

2,146.952 as a float is 2.000000

The comma seems to cause the float value to be rounded down, if I use doubleValue] it does the same.

Is there a way to get this to be 2146.952?

Upvotes: 1

Views: 1807

Answers (2)

vikingosegundo
vikingosegundo

Reputation: 52227

You should use a NSNumberFormatter.
if the format is always as show (source: Server api), set the decimalSeparator to . and the groutingSeparator to ,.

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setDecimalSeparator:@"."];
[numberFormatter setGroupingSeparator:@","];

NSNumber *number = [numberFormatter numberFromString:numberString];

if the string format depends somehow on the user preferences (input via keyboard), set the locale instead

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[NSLocale currentLocale]];
NSNumber *number = [numberFormatter numberFromString:numberString];

the second solution can also used for the first case, if you set a locale like

[numberFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

Upvotes: 5

Girish
Girish

Reputation: 4712

Try,

1) Remove the comma from the string as

NSString * str = [str stringByReplacingOccurencesOfString:@"," withString:@""];

2) Retrieve the float value from the string as

float f = [str floatValue];

Upvotes: 3

Related Questions