Objective-C中整數與字符串的相互轉換


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM