功能不多说了,直接上代码:
-(NSString *)notRounding:(float)price afterPoint:(int)position{
NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
NSDecimalNumber *ouncesDecimal;
NSDecimalNumber *roundedOunces;
ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
return [NSString stringWithFormat:@"%@",roundedOunces];
}
参数解释如下:
price:需要处理的数字,
position:保留小数点第几位,
然后调用
float s =0.126;
NSString *sb = [self notRounding:s afterPoint:2];
NSLog(@"sb = %@",sb);
输出结果为:sb = 0.12
接下来介绍NSDecimalNumberHandler初始化时的关键参数:decimalNumberHandlerWithRoundingMode:NSRoundDown,
NSRoundDown代表的就是 只舍不入。
scale的参数position代表保留小数点后几位。
以下是oc中直接存在的函数:
-向上取整:ceil(x),返回不小于x的最小整数;
-向下取整:floor(x),返回不大于x的最大整数;
-四舍五入:round(x)
-截尾取整函数:trunc(x)
网友评论