这个是系统方法
- (NSString*)Rounding:(float)number afterPoint:(NSInteger)position{ NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode: NSRoundPlain scale: position raiseOnExactness: NO raiseOnOverflow: NO raiseOnUnderflow:YES raiseOnDivideByZero: NO]; NSDecimalNumber *floatDecimal = [[NSDecimalNumber alloc] initWithFloat: number]; NSDecimalNumber *resultNumber = [floatDecimal decimalNumberByRoundingAccordingToBehavior:handler]; return [NSString stringWithFormat:@"%@",resultNumber];}
我用的是下面这个方法,注意⚠️只有在保留4位以下小数时四舍五入才正常
- (NSString*)Rounding:(double)number afterPoint:(NSInteger)position{ NSNumber *priceNum = [NSNumber numberWithDouble:number]; NSString *string = [NSString stringWithFormat:@"%.10f",number]; NSRange range = [string rangeOfString:@"."]; if (range.location!=NSNotFound) { NSInteger loc = range.location+position+1; NSRange rangeS; if (string.length>loc) { rangeS = NSMakeRange(loc, 1); NSString *str = [string substringWithRange:rangeS]; if (str!=nil&&[str floatValue]>=5.0f) { priceNum = [NSNumber numberWithDouble:[[string stringByReplacingCharactersInRange:rangeS withString:@"9"] floatValue]]; } } } if (position>4) { return @""; } if (position==1) {//保留1位 return [NSString stringWithFormat:@"%.1f",round([priceNum floatValue]*1000000000000)/1000000000000]; }else if(position==2){//保留2位 return [NSString stringWithFormat:@"%.2f",round([priceNum floatValue]*1000000000000)/1000000000000]; }else if(position==3){//保留3位 return [NSString stringWithFormat:@"%.3f",round([priceNum floatValue]*1000000000000)/1000000000000]; }else if(position==4){//保留4位 return [NSString stringWithFormat:@"%.4f",round([priceNum floatValue]*1000000000000)/1000000000000]; } //默认保留2位 return [NSString stringWithFormat:@"%.2f",round([priceNum floatValue]*1000000000000)/1000000000000];}
使用方法:
//保留小数点后2位,因为第3位小数大于5,所以第2位进1[self Rounding:100.11545 afterPoint:2]//结果返回 100.12//保留小数点后4位,因为第5位小数大于5,所以第4位进1[self Rounding: 100.11545 afterPoint:4]//100.1155//保留小数点后3位,因为第4位小数小于5,所以舍去[self Rounding: 100.11545 afterPoint:3]//100.115