开发者

specific number formatter to a phone number

开发者 https://www.devze.com 2023-04-03 06:46 出处:网络
I want to display the the number in the following format and the format is \"123-开发者_JAVA百科456-7890\"

I want to display the the number in the following format

and the format is "123-开发者_JAVA百科456-7890"

I am using

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

I am using the above code to do that but the code is not reflecting ..... and the out put appear as 1234567890 only can any body help how to do that.


Use this formatter:

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


in that code check the

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

as

tempStr = [NSString stringWithFormat:@"%@-%@-%@", areaCode, phone1, phone2]

in PhoneNumberFormatter.m


setPositiveFormat considers '-' separators to be minus signs.

Note: See Number Format Patterns

A work-around is to specify ',' separators and replace them:

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


Swift :

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消