3

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

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

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

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

我想,问题是逗号,但我无法摆脱那个逗号,因为它来自数据库。谁能帮我将此字符串格式转换为双精度或浮点数。

4

3 回答 3

8

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

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];
于 2015-08-12T15:16:56.147 回答
3

对此的解决方案实际上是删除逗号。尽管您最初是从数据库中获取这些逗号,但您可以在转换之前将它们删除。添加它作为从数据库获取数据并将其转换为双精度数据之间的附加步骤:

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
于 2015-08-12T15:11:31.297 回答
1

斯威夫特 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.

于 2020-10-26T06:24:35.827 回答