iOS开发中的NSDecimalNumber使用

好处

不会出现像字符串类型转float类型出现的错误。

  如:NSLog(@"%f", [@"123456700" floatValue]);

打印结果:

  123456704.000000

使用

  NSString * str = @"1";
NSLog(@"===%f", str.floatValue);

NSDecimalNumber * num1 = [NSDecimalNumber decimalNumberWithString:str];
// 保留小数点后两位
// // Rounding policies :
// Original
//    value 1.2  1.21  1.25  1.35  1.27
// Plain    1.2  1.2   1.3   1.4   1.3
// Down     1.2  1.2   1.2   1.3   1.2
// Up       1.2  1.3   1.3   1.4   1.3
// Bankers  1.2  1.2   1.2   1.4   1.3
NSDecimalNumberHandler *hander = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundBankers
              scale:1
   raiseOnExactness:NO
    raiseOnOverflow:NO
   raiseOnUnderflow:NO
raiseOnDivideByZero:YES];
NSDecimalNumber * amountYuan = [num1 decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"100"] withBehavior:hander];
NSLog(@"===%@", amountYuan);

NSLog(@"%@", [[NSDecimalNumber decimalNumberWithString:@"1.2"] decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"1"] withBehavior:hander]);
NSLog(@"%@", [[NSDecimalNumber decimalNumberWithString:@"1.21"] decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"1"] withBehavior:hander]);
NSLog(@"%@", [[NSDecimalNumber decimalNumberWithString:@"1.25"] decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"1"] withBehavior:hander]);
NSLog(@"%@", [[NSDecimalNumber decimalNumberWithString:@"1.35"] decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"1"] withBehavior:hander]);
NSLog(@"%@", [[NSDecimalNumber decimalNumberWithString:@"1.27"] decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"1"] withBehavior:hander]);

解释一下NSRoundingMode

  typedef NS_ENUM(NSUInteger, NSRoundingMode) {
NSRoundPlain,   // Round up on a tie
NSRoundDown,    // Always down == truncate
NSRoundUp,      // Always up
NSRoundBankers  // on a tie round so last digit is even
  };

该枚举类型有四个值
NSRoundPlain:保留位数的下一位四舍五入
NSRoundDown:保留位数的下一位直接舍去
NSRoundUp:保留位数的下一位直接进一位
NSRoundBankers:当保留位数的下一位不是5时,四舍五入,当保留位数的下一位是5时,其前一位是偶数直接舍去,是奇数直接进位(如果5后面还有数字则直接进位)

你可能感兴趣的:(iOS开发中的NSDecimalNumber使用)