iOS 四舍五入保留两位小数

通常我们四舍五入输出可能你会用NSString stringWithFormat函数%.2f方式,但是这个四舍五入有时可能不是四舍五入,而是五舍六入。其实有更精确的四舍五入方式。


先说一下最后确定使用的方法:(四舍五入,保留两位小数)

-(float)roundFloat:(float)price{

    return roundf(price*100)/100;

}

(保留1位小数100改为10,以此类推)

下面再说说这个曲折的过程,首先我想到的是用ios里面自带的round方法,

-(float)roundFloat:(float)price{

    return roundf(price);

}

但是如下举例

float test = 23.625;

float test2 = 23.6250;

float test3 = 23.6251;

test = [self roundFloat:test];

test2 = [self roundFloat:test2];

test3 = [self roundFloat:test3];

    

NSLog(@"test:%.2f",test);

NSLog(@"test2:%.2f",test2);

NSLog(@"test3:%.2f",test3);

得出结果:

test:24.00

test2:24.00

test3:24.00


很显然不是我想要的效果,经过改进便是如下结果,

-(float)roundFloat:(float)price{

    return roundf(price*100)/100;

}


有人说此方法不知在什么数据情况下会不准,还有个更保险的方法:

-(float)roundFloat:(float)price{

    return (floorf(price*100 + 0.5))/100;

}



iOS中round/ceil/floorf函数略解

extern float ceilf(float);

extern double ceil(double);

extern long double ceill(long double);


extern float floorf(float);

extern double floor(double);

extern long double floorl(longdouble);


extern float roundf(float);

extern double round(double);

extern long double roundl(longdouble);


round:如果参数是小数,则求本身的四舍五入。
ceil:如果参数是小数,则求最小的整数但不小于本身.(向上取整)
floor:如果参数是小数,则求最大的整数但不大于本身. (向下取整)

Example:如何值是3.4的话,则

3.4 -- round 3.000000

    -- ceil 4.000000

    -- floor 3.00000



猜你喜欢

转载自blog.csdn.net/txz_gray/article/details/71440256