iOS 四舍五入、进位、摸位 方法
2016-01-27 本文已影响5570人
龙翱天际
iOS开发中经常遇到 浮点数的 四舍五入、进位、摸位 方法。
1,四舍五入法
float numberToRound;
int result;
numberToRound = 5.61;
result = (int)roundf(numberToRound);
NSLog(@"roundf(%.2f) = %d", numberToRound, result);
//输出 roundf(5.61) = 6
numberToRound = 5.41;
result = (int)roundf(numberToRound);
NSLog(@"roundf(%.2f) = %d", numberToRound, result);
//输出 roundf(5.41) = 5
2、进位方法
float numberToRound;
int result;
numberToRound = 5.61;
result = (int)ceilf(numberToRound);
NSLog(@"ceilf(%.2f) = %d", numberToRound, result);
//输出 ceilf(5.61) = 6
numberToRound = 5.41;
result = (int)ceilf(numberToRound);
NSLog(@"ceilf(%.2f) = %d", numberToRound, result);
//输出 ceilf(5.41) = 6
3、摸位方法
float numberToRound;
int result;
numberToRound = 5.61;
result = (int)floorf(numberToRound);
NSLog(@"floorf(%.2f) = %d", numberToRound, result);
//输出 floorf(5.61) = 5
numberToRound = 5.41;
result = (int)floorf(numberToRound);
NSLog(@"floorf(%.2f) = %d", numberToRound, result);
//输出 floorf(5.41) = 5