不要丢失十进制值的最后一个零

时间:2015-07-29 12:18:33

标签: objective-c decimal nsnumberformatter

目前我的字符串输入看起来像:16904.489324.006806.10

我希望我的客户输出:16,904.489,324.006806.10

我写了以下代码:

-(NSString*)methodChangeNumberFormat:(NSString*)strGivenValue {

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

    NSNumber *nsNumTmp = [numberFormatter numberFromString:strGivenValue];

    NSString *strNumFormatted = [numberFormatter stringFromNumber:nsNumTmp];
    strNumFormatted = [NSString stringWithFormat:@"$%@",strNumFormatted];
    NSLog(@"formattedNumberString: %@", strNumFormatted);

    return strNumFormatted;
}

结果:16,904.489,3246,806.1

但这不是我想要的,请帮助我获得预期的结果。

现在,我跟随输入NSString。但我准备将输入更改为任何数据类型。

2 个答案:

答案 0 :(得分:0)

您应该设置数字格式化程序的属性。

[numberFormatter setMinimumFractionDigits:2];
[numberFormatter setGroupingSize:3];
[numberFormatter setGroupingSeparator:@","];

答案 1 :(得分:0)

有一些格式化程序样式可以完成您正在尝试完成的任务。尝试使用NSNumberFormatterCurrencyStyle

- (NSString *)methodChangeNumberFormat:(NSString*)strGivenValue {
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

    // Set decimal style and read given value
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *numberFromString = [numberFormatter numberFromString:strGivenValue];

    // Set currency style and produce formatted value
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSString *strNumFormatted = [numberFormatter stringFromNumber:numberFromString];
    NSLog(@"formattedNumberString: %@", strNumFormatted);

    return strNumFormatted;
}

输出:

formattedNumberString: $16,904.48
formattedNumberString: $9,324.00
formattedNumberString: $6,806.10