iOS四舍五入

计算进度时遇到的问题。7000/8000

        NSLog(@"%.0f",0.1249*100);
        NSLog(@"%.0f",0.125*100);
        NSLog(@"%.0f",0.1251*100);
        
        NSLog(@"%.0f",0.8749*100);
        NSLog(@"%.0f",0.875*100);
        NSLog(@"%.0f",0.8750*100);
        
        NSLog(@"%d",(int)(0.1249*100 + 0.5));
        NSLog(@"%d",(int)(0.125*100 + 0.5));
        NSLog(@"%d",(int)(0.1251*100 + 0.5));
        
        NSLog(@"%d",(int)(0.8749*100 + 0.5));
        NSLog(@"%d",(int)(0.875*100 + 0.5));
        NSLog(@"%d",(int)(0.8750*100 + 0.5));
2018-03-13 17:04:06.573370+0800 floatTest[7856:239888] 12
2018-03-13 17:04:06.573621+0800 floatTest[7856:239888] 12
2018-03-13 17:04:06.573637+0800 floatTest[7856:239888] 13
2018-03-13 17:04:06.573649+0800 floatTest[7856:239888] 87
2018-03-13 17:04:06.573662+0800 floatTest[7856:239888] 88
2018-03-13 17:04:06.573678+0800 floatTest[7856:239888] 88
2018-03-13 17:04:06.573691+0800 floatTest[7856:239888] 12
2018-03-13 17:04:06.573704+0800 floatTest[7856:239888] 13
2018-03-13 17:04:06.573719+0800 floatTest[7856:239888] 13
2018-03-13 17:04:06.573743+0800 floatTest[7856:239888] 87
2018-03-13 17:04:06.573760+0800 floatTest[7856:239888] 88
2018-03-13 17:04:06.573770+0800 floatTest[7856:239888] 88
Program ended with exit code: 0

Objective-C拓展了C,自然很多用法是和C一致的。比如浮点数转化成整数,就有以下四种情况。
1.简单粗暴,直接转化

float f = 1.5;
int a;
a = (int)f;
NSLog("a = %d",a);

输出结果是1。(int)是强制类型转化,丢弃浮点数的小数部分。

2.高斯函数,向下取整

float f = 1.6;
int a;
a = floor(f);
NSLog("a = %d",a);

输出结果是1。floor()方法是向下取整,类似于数学中的高斯函数 [].取得不大于浮点数的最大整数,对于正数来说是舍弃浮点数部分,对于复数来说,舍弃浮点数部分后再减1.

3.ceil函数,向上取整。

float f = 1.5;
int a;
a = ceil(f);
NSLog("a = %d",a);

输出结果是2。ceil()方法是向上取整,取得不小于浮点数的最小整数,对于正数来说是舍弃浮点数部分并加1,对于复数来说就是舍弃浮点数部分.

4.通过强制类型转换四舍五入。

float f = 1.5;
int a;
a = (int)(f+0.5);
NSLog("a = %d",a);

其中原理非常简单,所以就不做详细说明了。
参考:
http://blog.csdn.net/abc649395594/article/details/44730425

你可能感兴趣的:(iOS四舍五入)