特定号码格式化器到电话号码

时间:2011-09-08 10:54:49

标签: ios objective-c nsnumberformatter

我想以下列格式显示数字

,格式为“123-456-7890”

我正在使用

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterNoStyle];
[formatter setPositiveFormat:@"###-###-####"];
[formatter setLenient:YES];

amountField.text =[formatter stringFromNumber:[NSNumber numberWithDouble:[rxAlertResponse.rxPhoneNo doubleValue]]];
NSLog(@"%@",amountField.text);

我使用上面的代码来做到这一点,但是代码没有反映.....而且输出显示为1234567890只有任何身体可以帮助如何做到这一点。

4 个答案:

答案 0 :(得分:3)

使用此格式化程序:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
    //[formatter setNumberStyle:NSNumberFormatterNoStyle];
    //[formatter setPositiveFormat:@"###-###-####"]; 
    [formatter setGroupingSeparator:@"-"];
    [formatter setGroupingSize:4];
    [formatter setUsesGroupingSeparator:YES];
       [formatter setSecondaryGroupingSize:3];
    //[formatter setLenient:YES];
    NSString *num = @"1234567890";
    NSString *str = [formatter stringFromNumber:[NSNumber numberWithInt:[num intValue]]];
    NSLog(@"%@",str); 

答案 1 :(得分:1)

在该代码中 检查

tempStr = [NSString stringWithFormat:@"1(%@)%@-%@", areaCode, phone1, phone2];

作为

tempStr = [NSString stringWithFormat:@"%@-%@-%@", areaCode, phone1, phone2]
PhoneNumberFormatter.m中的

答案 2 :(得分:0)

setPositiveFormat将' - '分隔符视为减号。

注意:请参阅Number Format Patterns

解决方法是指定','分隔符并替换它们:

NSNumber *phoneNumber = [NSNumber numberWithDouble:[rxAlertResponse.rxPhoneNo doubleValue]];
NSString *text =[formatter stringFromNumber:phoneNumber];
amountField.text = [text stringByReplacingOccurrencesOfString:@"," withString:@"-"];

答案 3 :(得分:0)

快捷键:

let numberFormatter = NumberFormatter()
numberFormatter.groupingSeparator = "-"
numberFormatter.groupingSize = 4
numberFormatter.usesGroupingSeparator = true
numberFormatter.secondaryGroupingSize = 3
let number = "1234567890"
let formattedNumber = numberFormatter.string(from: NSNumber(value: Int(number)!))
print(formattedNumber as Any)