使用逗号时将字符串转换为双精度

问题描述 投票:0回答:3

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

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

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

这里我得到 1 而不是 1250.50。

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

ios objective-c nsstring double nsformatter
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];

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

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.
© www.soinside.com 2019 - 2024. All rights reserved.