NSDecimalNumberHandler 调试记录

项目中遇见精度问题, 代码给的 down 向下取整,但是当负数时候就会出错,变成向上取整

代码如下:

func number(string: String){
    
    //方式1:不进行四舍五入
    let number1 = NSDecimalNumber(string: string)
    let number2 = NSDecimalNumber(string: "0")
    let num = number1.adding(number2)
    print("num =>\(num.stringValue)")

    //方式2:进行四舍五入
    //scale四舍五入,舍入位数
    let scale:Int16 = 4
    var round = NSDecimalNumberHandler(roundingMode: .down, scale:scale , raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
   
    let down = number1.adding(number2, withBehavior: round)
    print("down =>\(down.stringValue)")
    
    
    round = NSDecimalNumberHandler(roundingMode: .up, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
   
    let Up = number1.adding(number2, withBehavior: round)
    print("Up =>\(Up.stringValue)")
    
    round = NSDecimalNumberHandler(roundingMode: .plain, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
   
    let plain = number1.adding(number2, withBehavior: round)
    print("plain =>\(plain.stringValue)")
}

number(string: "0.012369")
number(string: "-0.012369")

精度设置的第四位,打印结果如下:
num =>0.012369
down =>0.0123
Up =>0.0124
plain =>0.0124
===============================
num =>-0.012369
down =>-0.0124
Up =>-0.0123
plain =>-0.0124

可以看出来, 当负数时, down 时向上取整,Up 是 向下取整
所以对于负数 需要特殊处理

你可能感兴趣的:(NSDecimalNumberHandler 调试记录)