NSDecimalNumber使用小结
1. 小数点后多余0的处理
- (void)test1{
/**
* 要求:输出0.1
*/
NSString * str = @"0.1000";
NSDecimalNumber * result = [NSDecimalNumber decimalNumberWithString:str];
}
2. 小数点后n位处理
2.1四舍五入
- (void)test2{
/**
* 要求:a=0.127 b=0.13
*/
NSDecimalNumberHandler * handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
NSDecimalNumber * a = [NSDecimalNumber decimalNumberWithString:@"0.127"];
NSDecimalNumber * b = [a decimalNumberByRoundingAccordingToBehavior:handler];
NSLog(@"%@,%@",a,b);
}
2.2截取
将RoundMode改为NSRoundDown。
3.非空判断
- (void)test4{
NSString * str = nil;
NSDecimalNumber * n = [NSDecimalNumber decimalNumberWithString:str];
NSDecimalNumber * nan = [NSDecimalNumber notANumber];
if (n == nan) {
NSLog(@"数据为空:NaN");
}
}
当服务器返回的NSNumber类型的数据为空时,可通过上述方法进行判断。
网友评论