OtheriOS

iOS中数字的格式化 NSNumberFormatter

2016-03-22  本文已影响2382人  奋斗的蜗牛

NSNumberFormatter 和NSDateFormatter 是NsFormatter的子类。
NSNumberFormatter类有个属性numberStyle,它是一个枚举型,设置不同的值可以输出不同的数字格式。该枚举包括:

enum {
    NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle, //无格式,四舍五入,原值2.7999999999,直接输出3 
    NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle, //小数型,保留小数输出2.8
    NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle, //货币型,加上了人民币标志,原值输出¥2.8
    NSNumberFormatter
    NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,  //百分比型,本身数值乘以100后用百分号表示,输出280%
    NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle, //科学计数型,原值表示,输出2.799999999E0
    NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle  //全拼,原值的中文表示,输出二点七九九九...
};

typedef NSUInteger NSNumberFormatterStyle;

各个枚举对应输出数字格式的效果如下:

[1243:403] Formatted number string:123456789
[1243:403] Formatted number string:123,456,789
[1243:403] Formatted number string:¥123,456,789.00
[1243:403] Formatted number string:-539,222,988%
[1243:403] Formatted number string:1.23456789E8
[1243:403] Formatted number string:一亿二千三百四十五万六千七百八十九

其中第三项和最后一项的输出会根据系统设置的语言区域的不同而不同

/**
 *  @author liboy
 *
 *  格式化余额数据
 *
 *  @param string 余额数据字符串
 *
 *  @return 带逗号余额
 */
- (NSString *)balanceFormatFromStr:(NSString*)string
{
    NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
    [numFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumberFormatter *numFormatter2 = [[NSNumberFormatter alloc] init];
    [numFormatter2 setNumberStyle:NSNumberFormatterNoStyle];
    NSNumber *num = [numFormatter2 numberFromString:string];
    NSString *tempStr = [numFormatter stringFromNumber:num];
    NSString *balanceStr = [tempStr substringFromIndex:1];
    if ([tempStr hasPrefix:@"-"]) {
        balanceStr = [NSString stringWithFormat:@"-%@",[tempStr substringFromIndex:2]];
    }
    return balanceStr;
    
}
上一篇下一篇

猜你喜欢

热点阅读