关于NSDecimalNumber
// Immutable with no mutable subclasses
@interface NSDecimalNumber : NSNumber
NSDecimalNumber属于NSNumber的一个子类,并且是不可变的
官方介绍
NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.
翻译一下
NSDecimalNumber是NSNumber的一个不可变子类,它提供了一个面向对象的包装器,用于执行10进制算术。实例可以表示任何可以表示为尾数x 10^指数的数字,其中尾数是长达38位的十进制整数,指数是从-128到127的整数。
说白了,就是用于高精度计算
NSDecimalNumber初始化
实例方法初始化
// 使用给定的尾数、指数和符号初始化十进制数。
- (instancetype)initWithMantissa:(unsigned long long)mantissa exponent:(short)exponent isNegative:(BOOL)flag;
// 初始化十进制数以表示给定的十进制数。
- (instancetype)initWithDecimal:(NSDecimal)dcm NS_DESIGNATED_INITIALIZER;
// 初始化十进制数,使其值等价于给定数字字符串中的值。
- (instancetype)initWithString:(nullable NSString *)numberValue;
- (instancetype)initWithString:(nullable NSString *)numberValue locale:(nullable id)locale;
类方法初始化
// 使用给定的尾数、指数和符号初始化十进制数。
+ (NSDecimalNumber *)decimalNumberWithMantissa:(unsigned long long)mantissa exponent:(short)exponent isNegative:(BOOL)flag;
+ (NSDecimalNumber *)decimalNumberWithDecimal:(NSDecimal)dcm;
+ (NSDecimalNumber *)decimalNumberWithString:(nullable NSString *)numberValue;
+ (NSDecimalNumber *)decimalNumberWithString:(nullable NSString *)numberValue locale:(nullable id)locale;
这么几个初始化方法,看着还是这两个实用
- (instancetype)initWithString:(nullable NSString *)numberValue;
+ (NSDecimalNumber *)decimalNumberWithString:(nullable NSString *)numberValue;
NSDecimalNumber运算
系统方法中提供了6种运算方式,分别为
// 加
- (NSDecimalNumber *)decimalNumberByAdding:(NSDecimalNumber *)decimalNumber;
- (NSDecimalNumber *)decimalNumberByAdding:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;
// 减
- (NSDecimalNumber *)decimalNumberBySubtracting:(NSDecimalNumber *)decimalNumber;
- (NSDecimalNumber *)decimalNumberBySubtracting:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;
// 乘
- (NSDecimalNumber *)decimalNumberByMultiplyingBy:(NSDecimalNumber *)decimalNumber;
- (NSDecimalNumber *)decimalNumberByMultiplyingBy:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;
// 除
- (NSDecimalNumber *)decimalNumberByDividingBy:(NSDecimalNumber *)decimalNumber;
- (NSDecimalNumber *)decimalNumberByDividingBy:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;
// 幂次方
- (NSDecimalNumber *)decimalNumberByRaisingToPower:(NSUInteger)power;
- (NSDecimalNumber *)decimalNumberByRaisingToPower:(NSUInteger)power withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;
// 指数
- (NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power;
- (NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;
关于NSDecimalNumberBehaviors这个协议,看看官方解释
A protocol that declares three methods that control the discretionary aspects of working with decimal numbers.
The scale and roundingMode methods determine the precision of NSDecimalNumber’s return values and the way in which those values should be rounded to fit that precision. The exceptionDuringOperation:error:leftOperand:rightOperand: method determines the way in which an NSDecimalNumber object should handle different calculation errors.
For an example of a class that adopts the NSDecimalBehaviors protocol, see the specification for NSDecimalNumberHandler.
scale和roundingMode方法决定了NSDecimalNumber返回值的精度,以及这些值应该四舍五入以适应该精度的方式。方法决定了NSDecimalNumber对象处理不同计算错误的方式。
有关采用NSDecimalBehaviors协议的类的示例,请参阅NSDecimalNumberHandler的规范。
意思就是,NSDecimalNumberBehaviors这个东西可以控制数字的舍取方式,和保留的小数位数
再看看NSDecimalNumberHandler这个,官方解释
A class that adopts the decimal number behaviors protocol.// 采用十进制数字行为协议的类。
This class allows you to set the way an NSDecimalNumber object rounds off and handles errors, without having to create a custom class.
You can use an instance of this class as an argument to any of the NSDecimalNumber methods that end with ...Behavior:. If you don’t think you need special behavior, you probably don’t need this class—it is likely that NSDecimalNumber's default behavior will suit your needs.
这个类允许你设置NSDecimalNumber对象舍入和处理错误的方式,而不需要创建一个自定义类。
你可以使用这个类的实例作为任何以…行为结尾的NSDecimalNumber方法的参数。如果你认为你不需要特殊的行为,你可能不需要这个类——NSDecimalNumber的默认行为很可能会满足你的需求。
说白了,就是系统给了你一个NSDecimalNumberBehaviors协议的实例,直接用这个去实现NSDecimalNumberBehaviors协议就行了
// 默认的规则
/*
rounding mode :NSRoundPlain
scale :全精度(是多少位小数就是多少位)
忽略异常情况
*/
@property (class, readonly, strong) NSDecimalNumberHandler *defaultDecimalNumberHandler;
// 自定义舍取模式,保留的小数位数,是否抛溢出等情况
- (instancetype)initWithRoundingMode:(NSRoundingMode)roundingMode scale:(short)scale raiseOnExactness:(BOOL)exact raiseOnOverflow:(BOOL)overflow raiseOnUnderflow:(BOOL)underflow raiseOnDivideByZero:(BOOL)divideByZero NS_DESIGNATED_INITIALIZER;
+ (instancetype)decimalNumberHandlerWithRoundingMode:(NSRoundingMode)roundingMode scale:(short)scale raiseOnExactness:(BOOL)exact raiseOnOverflow:(BOOL)overflow raiseOnUnderflow:(BOOL)underflow raiseOnDivideByZero:(BOOL)divideByZero;
举个🌰
// 保留两位小数,四舍五入
NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode: NSRoundPlain
scale:2
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:YES];
这个类介绍完了,接下来就是进行封装
NSDecimalNumber封装
说是封装,还不如说就是把调用简化一下
为了方便这里创建一个NSString的分类,直接将字符串转换成NSDecimalNumber类型的
// .h
/// 转换为NSDecimalNumber数据
@property (nonatomic, copy, readonly) NSDecimalNumber *decimalValue;
// .m
- (NSDecimalNumber *)decimalValue {
return [NSDecimalNumber decimalNumberWithString:self];
}
思想是用函数式编程来实现
首先创建一个NSDecimalNumber的分类就叫DecimalNumber
然后定义一些属性分别处理加、减、乘、除、幂次方、指数、舍入方式
NSDecimalNumber+DecimalNumber.h
/// 加
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^add)(id number);
/// 减
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^reduce)(id number);
/// 乘
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^multiplied)(id number);
/// 除 如果除数为0,返回自身
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^divide)(id number);
/// 幂次方
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^raising)(NSUInteger power);
/// 指数
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^multiplyingByPower)(short power);
/// 舍入
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^rounding)(NSRoundingMode roundingMode, short scale);
NSDecimalNumber+DecimalNumber.m
/// 加
- (NSDecimalNumber * _Nullable (^)(id _Nonnull))add {
return ^NSDecimalNumber *(id number){
if ([number isKindOfClass:[NSDecimalNumber class]]) {
return [self decimalNumberByAdding:(NSDecimalNumber *)number];
} else if ([number isKindOfClass:[NSString class]]) {
return [self decimalNumberByAdding:((NSString *)number).decimalValue];
} else {
return [self decimalNumberByAdding:[number stringValue].decimalValue];
}
};
}
/// 减
- (NSDecimalNumber * _Nullable (^)(id _Nonnull))reduce {
return ^NSDecimalNumber *(id number){
if ([number isKindOfClass:[NSDecimalNumber class]]) {
return [self decimalNumberBySubtracting:(NSDecimalNumber *)number];
} else if ([number isKindOfClass:[NSString class]]) {
return [self decimalNumberBySubtracting:((NSString *)number).decimalValue];
} else {
return [self decimalNumberBySubtracting:[number stringValue].decimalValue];
}
};
}
/// 乘
- (NSDecimalNumber * _Nullable (^)(id _Nonnull))multiplied {
return ^NSDecimalNumber *(id number){
if ([number isKindOfClass:[NSDecimalNumber class]]) {
return [self decimalNumberByMultiplyingBy:(NSDecimalNumber *)number];
} else if ([number isKindOfClass:[NSString class]]) {
return [self decimalNumberByMultiplyingBy:((NSString *)number).decimalValue];
} else {
return [self decimalNumberByMultiplyingBy:[number stringValue].decimalValue];
}
};
}
/// 除
- (NSDecimalNumber * _Nullable (^)(id _Nonnull))divide {
return ^NSDecimalNumber *(id number){
if ([number isKindOfClass:[NSDecimalNumber class]]) {
return [self decimalNumberByDividingBy:(NSDecimalNumber *)number];
} else if ([number isKindOfClass:[NSString class]]) {
return [self decimalNumberByDividingBy:((NSString *)number).decimalValue];
} else {
return [self decimalNumberByDividingBy:[number stringValue].decimalValue];
}
};
}
/// 幂次方
- (NSDecimalNumber * _Nullable (^)(NSUInteger))raising {
return ^NSDecimalNumber *(NSUInteger power){
return [self decimalNumberByRaisingToPower:power];
};
}
/// 指数
- (NSDecimalNumber * _Nullable (^)(short))multiplyingByPower {
return ^NSDecimalNumber *(short power){
return [self decimalNumberByMultiplyingByPowerOf10:power];
};
}
/// 舍取方式
- (NSDecimalNumber * _Nullable (^)(NSRoundingMode, short))rounding {
return ^NSDecimalNumber *(NSRoundingMode roundingMode, short scale){
NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:roundingMode
scale:scale
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:YES];
return [self decimalNumberByRoundingAccordingToBehavior:handler];
};
}
这样就简单的封装好了
接下来看看使用
NSDecimalNumber *number = @"10.15".decimalValue;
NSDecimalNumber *newNumber = number.add(@"10.015").reduce(@"0.005").multiplied(@"1.01").divide(@"10").rounding(NSRoundPlain, 2);
解释:(10.15 + 10.015 - 0.005) x 1.01 / 10的结果保留两位小数四舍五入
结果:2.040000
DecimalNumber[10561:175487] 2.040000
有需要的,麻烦点个赞,谢谢
完整代码
NSDecimalNumber+DecimalNumber.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSString (DecimalNumber)
/// 转换为NSDecimalNumber数据
@property (nonatomic, copy, readonly) NSDecimalNumber *decimalValue;
@end
@interface NSDecimalNumber (DecimalNumber)
/// 加
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^add)(id number);
/// 减
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^reduce)(id number);
/// 乘
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^multiplied)(id number);
/// 除 如果除数为0,返回自身
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^divide)(id number);
/// 幂次方
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^raising)(NSUInteger power);
/// 指数
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^multiplyingByPower)(short power);
/// 舍入
@property (nonatomic, copy, readonly) NSDecimalNumber *_Nullable(^rounding)(NSRoundingMode roundingMode, short scale);
@end
NS_ASSUME_NONNULL_END
NSDecimalNumber+DecimalNumber.m
#import "NSDecimalNumber+DecimalNumber.h"
@implementation NSString (DecimalNumber)
- (NSDecimalNumber *)decimalValue {
return [NSDecimalNumber decimalNumberWithString:self];
}
@end
@implementation NSDecimalNumber (DecimalNumber)
/// 加
- (NSDecimalNumber * _Nullable (^)(id _Nonnull))add {
return ^NSDecimalNumber *(id number){
if ([number isKindOfClass:[NSDecimalNumber class]]) {
return [self decimalNumberByAdding:(NSDecimalNumber *)number];
} else if ([number isKindOfClass:[NSString class]]) {
return [self decimalNumberByAdding:((NSString *)number).decimalValue];
} else {
return [self decimalNumberByAdding:[number stringValue].decimalValue];
}
};
}
/// 减
- (NSDecimalNumber * _Nullable (^)(id _Nonnull))reduce {
return ^NSDecimalNumber *(id number){
if ([number isKindOfClass:[NSDecimalNumber class]]) {
return [self decimalNumberBySubtracting:(NSDecimalNumber *)number];
} else if ([number isKindOfClass:[NSString class]]) {
return [self decimalNumberBySubtracting:((NSString *)number).decimalValue];
} else {
return [self decimalNumberBySubtracting:[number stringValue].decimalValue];
}
};
}
/// 乘
- (NSDecimalNumber * _Nullable (^)(id _Nonnull))multiplied {
return ^NSDecimalNumber *(id number){
if ([number isKindOfClass:[NSDecimalNumber class]]) {
return [self decimalNumberByMultiplyingBy:(NSDecimalNumber *)number];
} else if ([number isKindOfClass:[NSString class]]) {
return [self decimalNumberByMultiplyingBy:((NSString *)number).decimalValue];
} else {
return [self decimalNumberByMultiplyingBy:[number stringValue].decimalValue];
}
};
}
/// 除
- (NSDecimalNumber * _Nullable (^)(id _Nonnull))divide {
return ^NSDecimalNumber *(id number){
if ([number isKindOfClass:[NSDecimalNumber class]]) {
return [self decimalNumberByDividingBy:(NSDecimalNumber *)number];
} else if ([number isKindOfClass:[NSString class]]) {
return [self decimalNumberByDividingBy:((NSString *)number).decimalValue];
} else {
return [self decimalNumberByDividingBy:[number stringValue].decimalValue];
}
};
}
/// 幂次方
- (NSDecimalNumber * _Nullable (^)(NSUInteger))raising {
return ^NSDecimalNumber *(NSUInteger power){
return [self decimalNumberByRaisingToPower:power];
};
}
/// 指数
- (NSDecimalNumber * _Nullable (^)(short))multiplyingByPower {
return ^NSDecimalNumber *(short power){
return [self decimalNumberByMultiplyingByPowerOf10:power];
};
}
/// 舍取方式
- (NSDecimalNumber * _Nullable (^)(NSRoundingMode, short))rounding {
return ^NSDecimalNumber *(NSRoundingMode roundingMode, short scale){
NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:roundingMode
scale:scale
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:YES];
return [self decimalNumberByRoundingAccordingToBehavior:handler];
};
}
@end