iOS中的数值处理问题

向上取整:float ceilf(float);    double ceil(double);

向下取整:float floorf(float);   double floor(double);

四舍五入:float roundf(float);  double round(double);

 

    CGFloat a = 3.3;
    CGFloat ceilA = ceilf(a);
    CGFloat floorA = floorf(a);
    CGFloat roundA = roundf(a);
    
    NSLog(@"%lf 向上取整为%lf, 向下取整为%lf, 四舍五入为%lf", a, ceilA, floorA, roundA);
    
    double b = 5.8;
    double ceilB = ceil(b);
    double floorB = floor(b);
    double roundB = round(b);
    
    NSLog(@"%lf 向上取整为%lf, 向下取整为%lf, 四舍五入为%lf", b, ceilB, floorB, roundB);
    
    CGFloat c = -3.3;
    CGFloat ceilC = ceilf(c);
    CGFloat floorC = floorf(c);
    CGFloat roundC = roundf(c);
    
    NSLog(@"%lf 向上取整为%lf, 向下取整为%lf, 四舍五入为%lf", c, ceilC, floorC, roundC);
    
    double d = -5.8;
    double ceilD = ceil(d);
    double floorD = floor(d);
    double roundD = round(d);
    
    NSLog(@"%lf 向上取整为%lf, 向下取整为%lf, 四舍五入为%lf", d, ceilD, floorD, roundD);


// 打印结果
2017-03-02 10:03:47.570 UsingWebView[88462:10650303] 3.300000 向上取整为4.000000, 向下取整为3.000000, 四舍五入为3.000000
2017-03-02 10:03:47.572 UsingWebView[88462:10650303] 5.800000 向上取整为6.000000, 向下取整为5.000000, 四舍五入为6.000000
2017-03-02 10:03:47.573 UsingWebView[88462:10650303] -3.300000 向上取整为-3.000000, 向下取整为-4.000000, 四舍五入为-3.000000
2017-03-02 10:03:47.573 UsingWebView[88462:10650303] -5.800000 向上取整为-5.000000, 向下取整为-6.000000, 四舍五入为-6.000000

原文出处 https://www.cnblogs.com/muzijie/p/6489149.html

 

必知的三个C函数

ceil(x)返回不小于x的最小整数值(然后转换为double型)。
floor(x)返回不大于x的最大整数值。
round(x)返回x的四舍五入整数值。

上面就是天花板函数、地板函数、四舍五入函数。

保留两位小数,四舍五入

    //保留两位小数,四舍五入
    CGFloat rounded_up = round(0.355 * 100) / 100;
    NSLog(@"%.2lf",rounded_up);
    
    
    //保留两位小数,直接进1(天花板函数)
    CGFloat rounded_up1 = ceilf(0.355 * 100) / 100;
    NSLog(@"%.2lf",rounded_up1);
    
    //保留两位小数,舍弃后面所有位数。(地板函数)
    CGFloat rounded_up2 = floor(0.355 * 100) / 100;
    NSLog(@"%.2lf",rounded_up2);

    //保留两位小数,四舍五入
    CGFloat rounded_up = round(0.354 * 100) / 100;
    NSLog(@"%.2lf",rounded_up);
    
    //保留两位小数,直接进1(天花板函数)
    CGFloat rounded_up1 = ceilf(0.354 * 100) / 100;
    NSLog(@"%.2lf",rounded_up1);
    
    //保留两位小数,舍弃后面所有位数。(地板函数)
    CGFloat rounded_up2 = floor(0.354 * 100) / 100;
    NSLog(@"%.2lf",rounded_up2);



作者:YM_1
链接:https://www.jianshu.com/p/5b87eda6fa65
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值