iOS 四舍五入、进位、抹位 方法

这篇博客介绍了在iOS开发中如何进行四舍五入、进位(向上取整)和抹位(向下取整)的操作。提供了相应的Objective-C代码实现,包括使用`powf`、`roundf`和`ceilf`函数进行不同精度的数值处理,并通过示例展示了具体应用,如5.25和5.55分别处理后的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#pragma mark - 四舍五入 例如:5.25输出5  5.55输出6

- (NSString *)floatRounded:(float)a withCount:(NSInteger)count{

    float val = powf(10,count);

    CGFloat roundA = roundf(a * val);    

    NSMutableString *result=[NSMutableString stringWithFormat:@"%lf",roundA];

    [result insertString:@"." atIndex:count];

    return result;

}

#pragma mark - 进位 例如:5.25和5.55都输出6

- (NSString *)floatRounded:(float)a withCount:(NSInteger)count{

    float val = powf(10,count);

    CGFloat roundA = ceilf(a * val);

    NSMutableString *result=[NSMutableString stringWithFormat:@"%lf",roundA];

    [result insertString:@"." atIndex:count];

    return result;

}

#pragma mark - 抹位 例如:5.25和5.55都输出5

- (NSString *)floatRounded:(float)a withCount:(NSInteger)count{

    float val = powf(10,count);

    CGFloat roundA = roundf(a * val);    

    NSMutableString *result=[NSMutableString stringWithFormat:@"%lf",roundA];

    [result insertString:@"." atIndex:count];

    return result;

}

 

floatnumberToRound;intresult; numberToRound = 5.61; result = (int)ceilf(numberToRound);NSLog(@"ceilf(%.2f) = %d", numberToRound, result);//输出 ceilf(5.61) = 6numberToRound = 5.41; result = (int)ceilf(numberToRound);NSLog(@"ceilf(%.2f) = %d", numberToRound, result);//输出 ceilf(5.41) = 6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值