Rounding NSDecimalNumber

后端 未结 4 521
深忆病人
深忆病人 2020-12-10 00:54

I\'m having the hardest time figuring out something that seems like it should be very simple. I need to accurately round an NSDecimalNumber to a particular number of decimal

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 01:40

    I got it working using the below code in Swift 3.

    let amount = NSDecimalNumber(string: "123.456789")
    let handler = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
    let roundedAmount = amount.rounding(accordingToBehavior: handler)
    

    Note the scale parameter, used to define the decimal places you need. Outlined here: https://developer.apple.com/reference/foundation/nsdecimalnumberhandler/1578295-decimalnumberhandlerwithrounding

提交回复
热议问题