昨天发现给一个浮点型转百分比的时候会自动四舍五入。
//测试代码
NSString *str = @"0.032555";
DebugLog(@"取值=== %.2f%%",[str floatValue]*100);
打印: 取值=== 3.26%
而我想要的值是 3.25% 后来百度了下解决方案:
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 = [ouncesDecimaldecimalNumberByRoundingAccordingToBehavior:roundingBehavior];
return [NSString stringWithFormat:@"%@",roundedOunces];
主要设置成 NSRoundDown ,但是后来发现还是有问题,本来是4.56% 结果取出来是4.55%。 最后自己写了一个方法
我的方案如下:
#pragma mark -- float不自动四舍五入
///float不自动四舍五入
/// @param price 数字字符串
/// @param position 转百分比 取小数点后几位
-(NSString*)notRounding:(NSString*)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];
NSString*result =@"";
price = [NSString stringWithFormat:@"%f",[price doubleValue]*100];
if([price containsString:@"."]) {//有小数点
NSArray *array = [price componentsSeparatedByString:@"."];
NSString*lastStr = array.lastObject;
if(lastStr.length>position) {//小数点后的值的位数大于要取的位数,直接截取
lastStr = [lastStr substringToIndex:position];
}else{//小数点后的值的位数小于要取的位数,不够补零
NSInteger count = lastStr.length- (position);
NSString*zeroStr =@"";
for(int i =0; i < count; i++) {
zeroStr = [NSString stringWithFormat:@"%@0",zeroStr];
}
lastStr = [NSString stringWithFormat:@"%@%@",lastStr,zeroStr];
}
result = [NSString stringWithFormat:@"%@.%@",array.firstObject,lastStr];
}else{//没小数点的数,小数点后面 补零
NSString*lastStr =@"";
for(int i =0; i < position; i++) {
lastStr = [NSString stringWithFormat:@"%@0",lastStr];
}
result = [NSString stringWithFormat:@"%@.%@",price,lastStr];
}
return [NSString stringWithFormat:@"%@%%",result];;
}
取出来的值就正常了
网友评论