美文网首页
iOS 精准计算之 NSDecimalNumber

iOS 精准计算之 NSDecimalNumber

作者: 新生代农民工No1 | 来源:发表于2021-10-31 17:12 被阅读0次

    在有些场景下,我们需要精确到每一个小数点,而有些地方则需要显示最大的小数位;

    如:[NSString stringWithFormat:@"%.2f",2000/100] 最终显示的是20.00 ,而需求则是显示20;

    NSDecimalNumber

    NSDecimalNumber 是iOS中处理精准计算的Number类;在一般的货币计算中,苹果推荐使用这个类;
    下面将介绍下常用的方法:

    • +
    - (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;
    
    • x
    - (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;
    
    • 10的次方运算
    - (NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power;
    - (NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;
    
    • 比较
    - (NSComparisonResult)compare:(NSNumber *)decimalNumber;
    

    NSDecimalNumberHandler

    这个类允许设置NSDecimalNumber对象四舍五入和处理错误的方式,而不必创建自定义类。

    /*
      roundingMode:NSRoundPlain、NSRoundDown、NSRoundUp、NSRoundBankers
      scale: 小数点后的位数
      raiseOnExactness:如果YES,发生精准错误,处理程序将引发异常;否则忽略错误;
      raiseOnOverflow: 如果YES,发生溢出错误,处理程序将引发异常;否则忽略错误;
      raiseOnUnderflow: 如果YES,发生向下溢出错误,处理程序将引发异常;否则忽略错误;
      raiseOnDivideByZero:如果YES,发生除零错误,处理程序将引发异常;否则忽略错误;
    **/
    + (instancetype)decimalNumberHandlerWithRoundingMode:(NSRoundingMode)roundingMode  scale:(short)scale  raiseOnExactness:(BOOL)exact  raiseOnOverflow:(BOOL)overflow  raiseOnUnderflow:(BOOL)underflow  raiseOnDivideByZero:(BOOL)divideByZero;
    
    

    相关文章

      网友评论

          本文标题:iOS 精准计算之 NSDecimalNumber

          本文链接:https://www.haomeiwen.com/subject/neyznltx.html