前言:
1.项目里涉及到了金额
2.我们的金额是整数,单位是 分
需求
格式化金额, 分转元,保留两位小数,加上人民币符号,三位一个逗号,于是我写了个函数。
- (NSString *)formatToTwoDecimal:(id)count {
NSString *originNumber;
if ([count isKindOfClass:[NSString class]] || [count isKindOfClass:[NSNumber class]]) {
NSInteger i = [count integerValue];
originNumber = [NSString stringWithFormat:@"%ld",(long)i];
} else {
return @"¥0.00";
}
NSDecimalNumber *one = [NSDecimalNumber decimalNumberWithString:originNumber];
NSDecimalNumber *two = [NSDecimalNumber decimalNumberWithString:@"100"];
NSDecimalNumber *thr = [one decimalNumberByDividingBy:two];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
formatter.positiveFormat = @",###.##";
NSString *money = [formatter stringFromNumber:[NSNumber numberWithDouble:[thr doubleValue]]];
NSString *result = [NSString stringWithFormat:@"¥%@",money];
if (![result containsString:@"."]) { //被整除的情况
result = [NSString stringWithFormat:@"%@.00",result];
} else { //小数不足两位
NSArray *array = [result componentsSeparatedByString:@"."];
NSString *subNumber = array.lastObject;
if (subNumber.length == 1) {
result = [NSString stringWithFormat:@"%@.%@0",array.firstObject, array.lastObject];
}
}
return result;
}
测试截图
感谢 iOS 玩家:
iOS - 格式化金额,三位一逗号
iOS数字格式化为每隔三位用逗号隔开