问题
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.
回答1:
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
回答2:
You can use number formatter like this;
NSString * price = @"1,250.50";
NSNumberFormatter * numberFormatter = [NSNumberFormatter new];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setGroupingSeparator:@","];
[numberFormatter setDecimalSeparator:@"."];
NSNumber * number = [numberFormatter numberFromString:price];
double priceInDouble = [number doubleValue];
回答3:
Swift 5
let price = priceField.text //price is @"1,250.50"
let priceWithoutCommas = price.replacingOccurrences(of: ",", with: "") //price is @"1250.50"
let priceInDouble = Double(priceWithoutCommas) ?? 0.0 //price is 1250.
来源:https://stackoverflow.com/questions/31968931/convert-string-to-double-when-comma-is-used