使用 fmod()实现 iOS金额自适应小数点

+ (NSString *)fommatMoney:(NSNumber *)money{

    // 判断是否null 若是赋值为0 防止崩溃

    if (([money isEqual:[NSNull null]] || money == nil)) {

        money = @0;

    }

    CGFloat f = money.floatValue;

    if (fmodf(f, 1)==0) {

        //余数无小数

        return [NSString stringWithFormat:@"¥%.0f",f];

    } else if (fmodf(f*10, 1)==0) {

       //money*10的情况下 余数为0。返回一位小数

        return [NSString stringWithFormat:@"¥%.1f",f];

    } else {

        //余数为2位及以上小数返回两位小数

        return [NSString stringWithFormat:@"¥%.2f",f];

    }

}

C 库函数 - fmod()

C 库函数double fmod(double x, double y)返回x除以y的余数。

x-- 代表分子的浮点值。

y-- 代表分母的浮点值。

该函数返回 x/y 的余数。

演示

- (void)viewDidLoad {
    [super viewDidLoad];
    CGFloat a, b;
    NSInteger c;
    a = 9.2;
    b = 10;
    c = 1;
    NSLog(@"%f/%ld的余数是%f\n",a,c, fmod(a, c));
    NSLog(@"%f/%ld的余数是%f\n",a,c, fmod(a*10, c));
}

你可能感兴趣的:(使用 fmod()实现 iOS金额自适应小数点)