How to convert NSNumber to NSString
所以我有一个
1 2 3 4 | - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { DetailViewController *details = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil]; details.subjectText = [[myArray objectAtIndex:indexPath.row] objectForKey:@"subject"]; |
subjecttext的作品。但
尝试:
1 | NSString *myString = [NSNumber stringValue]; |
您可以通过以下方式完成:
1 2 | NSNumber *myNumber = @15; NSString *myNumberInString = [myNumber stringValue]; |
1 2 3 4 5 6 7 | //An example of implementation : // we set the score of one player to a value [Game getCurrent].scorePlayer1 = [NSNumber numberWithInteger:1]; // We copy the value in a NSNumber NSNumber *aNumber = [Game getCurrent].scorePlayer1; // Conversion of the NSNumber aNumber to a String with stringValue NSString *StringScorePlayer1 = [aNumber stringValue]; |
或者试试
在斯威夫特3
1 2 3 | let number:NSNumber = 25 let strValue = String(describing: number as NSNumber) print("As String => \(strValue)") |
我们可以得到字符串中的数值。
你可以这样迅速地
1 2 | let number : NSNumber = 95 let str : String = number.stringValue |
有趣的是,如果nsnumber成为字符串的一部分,它会自动转换为字符串。我认为没有文件记录。试试这些:
1 2 3 4 5 6 7 | NSLog(@"My integer NSNumber:%@",[NSNumber numberWithInt:184]); NSLog(@"My float NSNumber:%@",[NSNumber numberWithFloat:12.23f]); NSLog(@"My bool(YES) NSNumber:%@",[NSNumber numberWithBool:YES]); NSLog(@"My bool(NO) NSNumber:%@",[NSNumber numberWithBool:NO]); NSString *myStringWithNumbers = [NSString stringWithFormat:@"Int:%@, Float:%@ Bool:%@",[NSNumber numberWithInt:132],[NSNumber numberWithFloat:-4.823f],[NSNumber numberWithBool:YES]]; NSLog(@"%@",myStringWithNumbers); |
它将打印:
1 2 3 4 5 | My integer NSNumber:184 My float NSNumber:12.23 My bool(YES) NSNumber:1 My bool(NO) NSNumber:0 Int:132, Float:-4.823 Bool:1 |
适用于Mac和iOS
这个不起作用:
1 | NSString *myNSNumber2 = [NSNumber numberWithFloat:-34512.23f]; |