【问题标题】:Convert String to double when comma is used使用逗号时将字符串转换为双精度
【发布时间】:2015-08-12 15:02:44
【问题描述】:

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

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

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

这里我得到 1 而不是 1250.50。

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

【问题讨论】:

  • 请考虑您的国际用户。不是每个人都希望看到以这种方式格式化的数字。对于某些用户,数字1250.50 应格式化为1 250,00 或许多其他可能的格式。请务必使用NSNumberFormatter 以确保以适合其区域设置的格式向用户显示数字。

标签: ios objective-c nsstring double nsformatter


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • 另外,这不是您的问题的一部分,但它可能很快就会出现:并非所有十进制数都可以用二进制准确表示,这是创建双精度时真正使用的。如果您在转换后发现某些双打似乎有误,请参阅:stackoverflow.com/questions/6927132/nsstring-to-double-issue
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 2020-10-03
      相关资源
      最近更新 更多