传一个保留三位小数的浮点型数据给后台,不能是字符串。传给后台的都是对象,要么NSString,要么NSNumber。只能使用苹果提供的NSDecimalNumber。
- 浮点型数据转NSDecimalNumber。scale为保留的小数位数。
//方式1:不进行四舍五入
self.number1 = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",3.155999]];
self.number2 = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",6.1]];
NSDecimalNumber *num = [self.number2 decimalNumberByAdding:self.number1];
NSLog(@"num===%@",num);
num===9.255998999999999
//方式2:进行四舍五入
//NSRoundUp属性使所有的操作算到最近的位置,其他的进位选项是NSRoundPlain, NSRoundDown, 和 NSRoundBankers,它们都被定义在NSRoundingMode,scale参数定义了结果值保留的小数位的数量,其余的参数给所有的操作定义了异常处理行为.
//scale四舍五入,舍入位数
NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:3 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
NSDecimalNumber *num0 = [self.number2 decimalNumberByAdding:self.number1 withBehavior:roundUp];
self.number1 = [self.number1 decimalNumberByRoundingAccordingToBehavior:roundUp];
NSLog(@"num0===%@,self.number1=%@",num0,self.number1);
num0===9.256,self.number1=3.156
网友评论