如何将整数转换为objective-c中的相应单词? [英] How do I convert an integer to the corresponding words in objective-c?
问题描述
在iOS上的Objective-C中是否有一种方法可以将整数作为文本拼出?
Is there a way in Objective-C on iOS to spell out an integer number as text?
例如,如果我有
NSInteger someNumber = 11242043;
我想知道一些函数,以便返回一个类似于十一二百四十的字符串两千四十三。
I would like to know some function so that would return a string similar to "eleven million two hundred forty two thousand forty three."
推荐答案
Apple为许多数据类型内置了许多方便的格式化功能。称为格式化程序,它们可以将对象转换为字符串表示形式。
Apple has a lot of handy formatting functionality built in for many data types. Called a "formatter," they can convert objects to/from string representations.
对于您的情况,您将使用NSNumberFormatter,但如果您有一个整数,则需要首先将其转换为NSNumber。见下面的例子。
For your case, you will be using NSNumberFormatter, but if you have an integer you need to convert it to an NSNumber first. See below example.
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
如果你想要了解有关格式化程序的更多信息:
https://developer.apple.com/library/content/documentation/General/Conceptual/Devpedia-CocoaApp/Formatter.html
If you'd like to learn more about formatters: https://developer.apple.com/library/content/documentation/General/Conceptual/Devpedia-CocoaApp/Formatter.html
这篇关于如何将整数转换为objective-c中的相应单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!