使用逗号时将 String 转换为 double

Convert String to double when comma is used

我有一个 UITextfield,它由数据库中的数据填充。该值的格式为小数部分用逗号分隔。所以,结构类似于 1,250.50

我将数据保存在一个字符串中,当我尝试使用 doubleValue 方法将字符串转换为双精度或浮点数时。我得到 1。这是我的代码。

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

在这里我得到 1 而不是 1250.50。

我想,问题出在逗号上,但我无法删除该逗号,因为它来自数据库。谁能帮我把这个字符串格式转换成双精度或浮点数。

解决这个问题的真正方法是删除逗号。虽然您最初是从数据库中获取这些逗号,但您可以在转换前删除它们。添加它作为从数据库获取数据并将其转换为双精度数据之间的附加步骤:

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

您可以像这样使用数字格式化程序;

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];

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.