/******高级方法 ********/
[objc]view plaincopy
如何只舍不入。比如floatprice =0.126,怎么样才能得到0.12?
当然,通过字符串截取的办法肯定也能达到相同的效果。但是就是这么一个简单的问题要通过一些判断和截取才能获得结果,总感觉有点笨拙。
下面先给出该问题的解决办法:
-(NSString*)notRounding:(float)priceafterPoint:(int)position{
NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandlerdecimalNumberHandlerWithRoundingMode:NSRoundDownscale:positionraiseOnExactness:NOraiseOnOverflow:NOraiseOnUnderflow:NOraiseOnDivideByZero:NO];
NSDecimalNumber*ouncesDecimal;
NSDecimalNumber*roundedOunces;
ouncesDecimal = [[NSDecimalNumberalloc]initWithFloat:price];
roundedOunces = [ouncesDecimaldecimalNumberByRoundingAccordingToBehavior:roundingBehavior];
[ouncesDecimalrelease];
return[NSStringstringWithFormat:@"%@",roundedOunces];
}
介绍一下参数:
price:需要处理的数字,
position:保留小数点第几位,
然后调用
floats =0.126;
NSString*sv = [selfnotRounding:safterPoint:2];
NSLog(@"sv = %@",sv);
输出结果为:sv =0.12
接下来介绍NSDecimalNumberHandler初始化时的关键参数:decimalNumberHandlerWithRoundingMode:NSRoundDown,
NSRoundDown代表的就是 只舍不入。
scale的参数position代表保留小数点后几位。
介绍一下参数:
price:需要处理的数字,
position:保留小数点第几位,
然后调用
float s =0.126;
NSString *sv = [self notRounding:s afterPoint:2];
NSLog(@"sv = %@",sv);
输出结果为:sv = 0.12
接下来介绍NSDecimalNumberHandler初始化时的关键参数:decimalNumberHandlerWithRoundingMode:NSRoundDown,
NSRoundDown代表的就是只舍不入。
scale的参数position代表保留小数点后几位。
/****** c 方法 *********/
1,四舍五入法
floatnumberToRound;
intresult;
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、进位方法
floatnumberToRound;
intresult;
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、摸位方法
floatnumberToRound;
intresult;
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
转载自:http://www.cnblogs.com/yingkong1987/archive/2012/12/18/2823077.html