1. Objective-C:
double testNum = 367.12459;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
/// 拼写输出中文
formatter.numberStyle = kCFNumberFormatterSpellOutStyle;
/// 如果不设置locle 跟随系统语言
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
NSString *spellOutStr = [formatter stringFromNumber:[NSNumber numberWithDouble: testNum]];
NSLog(@"SpellOut 中文: %@", spellOutStr);
/// 拼写输出英文
formatter.numberStyle = kCFNumberFormatterSpellOutStyle;
/// 如果不设置locle 跟随系统语言
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString *spellOutStrEn = [formatter stringFromNumber:[NSNumber numberWithDouble: testNum]];
NSLog(@"SpellOut 英文: %@", spellOutStrEn);
2. Swift5
let number = 367.12459
let numberFormatter = NumberFormatter()
/// 如果不设置locle 跟随系统语言
numberFormatter.locale = Locale(identifier: "zh_CN")
numberFormatter.numberStyle = NumberFormatter.Style.spellOut
let numberStr = numberFormatter.string(from: NSNumber(value: number)) ?? ""
print(numberStr)
枚举类型说明
- None:无类型 输出:
- Decimal:取小数点后三位 输出:367.125
- Currency:格式化为货币(保留两位小数),货币符号跟随Locale 输出:$367.12 (或 ¥367.12)
- Percent:格式化为百分数(保留两位小数) 输出:36,712%
- Scientific:格式化为科学计数法 输出:3.6712459E2
- SpellOut:格式化拼写格式 ,中英文跟随Locale 输出:三百六十七点一二四五九 (或three hundred sixty-seven point one two four five nine)
- Ordinal:格式化为序号(保留整数),中英文跟随Locale 输出:368th (或 第367)
- CurrencyISOCode:格式化为货币标准码 输出:USD 367.12
- CurrencyPlural:格式化为货币 输出:367.12 US dollars (或 367.12 人民币)**
- CurrencyAccounting:格式化为货币会计 输出:$367.12
CFNumberFormatterStyle
1. Objective-C:
typedef CF_ENUM(CFIndex, CFNumberFormatterStyle) { // number format styles
kCFNumberFormatterNoStyle = 0,
kCFNumberFormatterDecimalStyle = 1,
kCFNumberFormatterCurrencyStyle = 2,
kCFNumberFormatterPercentStyle = 3,
kCFNumberFormatterScientificStyle = 4,
kCFNumberFormatterSpellOutStyle = 5,
kCFNumberFormatterOrdinalStyle API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)) = 6,
kCFNumberFormatterCurrencyISOCodeStyle API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)) = 8,
kCFNumberFormatterCurrencyPluralStyle API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)) = 9,
kCFNumberFormatterCurrencyAccountingStyle API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)) = 10,
};
2. Swift
extension NumberFormatter {
public enum Style : UInt {
case none
case decimal
case currency
case percent
case scientific
case spellOut
@available(iOS 9.0, *)
case ordinal
@available(iOS 9.0, *)
case currencyISOCode
@available(iOS 9.0, *)
case currencyPlural
@available(iOS 9.0, *)
case currencyAccounting
}
}