Objective-C中整数与字符串的相互转换

2019/01/03 16:53
阅读数 13

2013/4/15整理:

 

将整数转换成字符串 Convert Integer to NSString:
方法一:
int Value = 112233;
NSString *ValueString = [NSString stringWithFormat:@"%d", Value];
方法二:
[[NSNumber numberWithInt: 123] stringValue];
 
得到C风格的字符串 C String
char *ValueasCString = (char *)[ValueString UTF8String];
 
将字符串转换成整数或浮点数
Convert String to Integer or float
NSString has some useful methods:
-(int) intValue
-(float) floatValue
NSString *aNumberString = @"123";
int i = [aNumberString intValue];
 
字符串转换为日期
NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设定时间格式,这里可以设置成自己需要的格式
NSDate *date =[dateFormat dateFromString:@"1980-01-01 00:00:01"];
 
日期转换为字符串
NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设定时间格式,这里可以设置成自己需要的格式
NSString *currentDateStr = [dateFormat stringFromDate:[NSDate date]];

 

使用NSNumberFormatter将数值转换成字符串
Simplifying NSNumberFormatter Use on the iPhone With Objective-C Categories
Here are the different formatter styles, and the result when converting [NSNumber numberWithDouble:123.4] into an NSString.
NSNumberFormatterNoStyle (123)
NSNumberFormatterDecimalStyle (123.4)
NSNumberFormatterCurrencyStyle ($123.40)
NSNumberFormatterPercentStyle (12,340%)
NSNumberFormatterScientificStyle (1.234E2)
NSNumberFormatterSpellOutStyle (one hundred and twenty-three point four)
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
NSString *string = [formatter stringFromNumber:number];
[formatter release];
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部