0
我正在尋找一種算法或函數來分別將整數0,1,2轉換爲零,一,二。我們如何在Objective-C中做到這一點?算法將1轉換爲「一」等在objective-c
我正在尋找一種算法或函數來分別將整數0,1,2轉換爲零,一,二。我們如何在Objective-C中做到這一點?算法將1轉換爲「一」等在objective-c
Apple爲許多數據類型內置了許多方便的格式化功能。稱爲「格式化程序」,他們可以將對象轉換爲字符串表示或從字符串表示轉換對象。
對於您的情況,您將使用NSNumberFormatter,但是如果您有一個整數,則需要先將其轉換爲NSNumber。看下面的例子。
NSInteger anInt = 11242043;
NSString *wordNumber;
//convert to words
NSNumber *numberValue = [NSNumber numberWithInt:anInt]; //needs to be NSNumber!
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
wordNumber = [numberFormatter stringFromNumber:numberValue];
NSLog(@"Answer: %@", wordNumber);
// Answer: eleven million two hundred forty-two thousand forty-three
這是我的代碼爲0到100(您可以根據您的要求更新)。完美的工作!
-(NSDictionary *)algorithm
{
NSArray *myArray = @[@"Zero",@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine",@"Ten",@"Eleven",@"Twelve",@"Thirteen",@"Fourteen",@"Fifteen",@"Sixteen",@"Sevteen",@"Eighteen",@"Nineteen"];
NSArray *tensArray = @[@"Twenty",@"Thirty",@"Fourty",@"Fifty",@"Sixty"
,@"Seventy",@"Eighty",@"Ninety",@"One Hundred"];
NSMutableDictionary *numberStringDictionary = [[NSMutableDictionary alloc] init];
NSMutableArray *numberStringsArray = [[NSMutableArray alloc] init];
for(int i=0;i<=100;i++)
{
if(i<20)
{
[numberStringDictionary setObject:myArray[i] forKey:[NSString stringWithFormat:@"%d",i]];
[numberStringsArray addObject:myArray[i]];
NSLog(@"\n%@",myArray[i]);
}
else if(i%10==0)
{
[numberStringDictionary setObject:tensArray[i/10-2] forKey:[NSString stringWithFormat:@"%d",i]];
[numberStringsArray addObject:tensArray[i/10-2]];
NSLog(@"\n%@",tensArray[i/10-2]);
}
else
{
[numberStringDictionary setObject:[NSString stringWithFormat:@"%@ %@",tensArray[i/10-2],myArray[i%10]] forKey:[NSString stringWithFormat:@"%d",i]];
[numberStringsArray addObject:[NSString stringWithFormat:@"%@ %@",tensArray[i/10-2],myArray[i%10]]];
NSLog(@"%@",[NSString stringWithFormat:@"%@ %@",tensArray[i/10-2],myArray[i%10]]);
}
}
return numberStringDictionary;
}
僅限於單個數字?只有本地化或英語? – rounak
http://stackoverflow.com/questions/3911966/how-to-convert-number-to-words-in-java。這是java – AdamM
@AdamM感謝好友的代碼示例。我將轉換代碼 –