【问题标题】:Large number not correct from UITextFieldUITextField 中的大数字不正确
【发布时间】:2014-04-25 04:09:41
【问题描述】:

我有一个应用程序,它有一个 UITextField,用户输入一个电话号码,然后点击通话按钮,然后调用此方法。

- (IBAction)callVendor:(id)sender {
    NSString *phoneNumber = [NSString stringWithFormat:@"tel:%f", 
       self.phoneTextField.text.doubleValue];
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:phoneNumber]];
}

当我尝试使用 .intValue 创建字符串时,电话号码完全关闭。我拨的是德克萨斯州而不是堪萨斯州!

当我尝试使用双精度时,我得到的数字更大,因为 NSURL 类忽略了我猜的小数。所以我拨打类似 555-555-5555-000000

当我使用浮点数时,会出现舍入错误。类似 555-555-5634-000000 而不是 555-555-5555-000000。我认为这是由于二进制 -> base-10 舍入误差。

我不想将其截断为 10 个号码,以防我需要拨打国际电话或无区号。我在这里有什么选择?

【问题讨论】:

    标签: iphone nsurl


    【解决方案1】:

    您能做的最好的事情就是将电话号码作为 NSString 传递。为什么要转换成数字?它甚至可以包含一个 + 号。 您可以通过以下方式修剪所有不需要的字符:

    NSCharacterSet *charactersToRemove = [[NSCharacterSet characterSetWithCharactersInString:@"+0123456789"] invertedSet];
    NSString *newPhoneNumber = [[self.phoneTextField.text componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];
    newPhoneNumber = [NSString stringWithFormat:@"tel:%@", newPhoneNumber];
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:newPhoneNumber]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-01
      • 2010-09-25
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 2012-03-18
      • 1970-01-01
      相关资源
      最近更新 更多