iOS 高精度计算NSDecimalNumber简单封装

关于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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,029评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,395评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,570评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,535评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,650评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,850评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,006评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,747评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,207评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,536评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,683评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,342评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,964评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,772评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,004评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,401评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,566评论 2 349

推荐阅读更多精彩内容