Search code examples
iosobjective-cnsstringdoublensformatter

Convert String to double when comma is used


I have a UITextfield and it is being populated by data from database. The value is formatted in a way that the fractional part is separated by comma. So, the Structure is something like 1,250.50

I save the data in a string and when I try to use the doubleValue method to convert the string to a double or floating number. I am getting 1. Here is my code.

NSString *price = self.priceField.text; //here price = 1,250.50
double priceInDouble = [price doubleValue];

Here I get 1 instead of 1250.50.

I guess, the issue is the comma, but I can't get rid of that comma as it is coming from the database. Can anyone please help me to convert this string format to double or float.


Solution

  • The solution on this really is to remove the commas. Although you are originally getting those commas from the database, you can just remove them before conversion. Add it as an additional step in between getting the data from the DB and converting it to a double:

    NSString *price = self.priceField.text;  //price is @"1,250.50"
    NSString *priceWithoutCommas = [price stringByReplacingOccurrencesOfString:@"," withString:@""];  //price is @"1250.50"
    double priceInDouble = [priceWithoutCommas doubleValue]; //price is 1250.50