How to round an NSDecimalNumber in swift?

倖福魔咒の 提交于 2019-11-29 09:32:56

you can do it like that

let x = 5
let y = 2
let total = x.decimalNumberByDividingBy(y).decimalNumberByRoundingAccordingToBehavior( NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundUp, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false))   

NSDecimalNumberBehaviors is a protocol and thus cannot be instantiated. You need an object of a class conforming to the protocol. Apple provides the class NSDecimalNumberHandler for this purpose, e.g.:

let handler = NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundBankers, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let rounded = dec.decimalNumberByRoundingAccordingToBehavior(handler)

The scale argument is the number of decimals you want, i.e., 0 rounds to an integer.

// get a decimal num from a string

let num = NSDecimalNumber.init(string: numStr)

// create an NSDecimalNumberHandler instance 

let behaviour = NSDecimalNumberHandler(roundingMode:.RoundUp, 
scale: 1, raiseOnExactness: false, 
raiseOnOverflow: false, raiseOnUnderflow: 
false, raiseOnDivideByZero: false)

// pass the handler to the method decimalNumberByRoundingAccordingToBehaviour.

// This is an instance method on NSDecimalNumber that takes an object that
// conforms to the protocol NSDecimalNumberBehaviors, which NSDecimalNumberHandler does!

let numRounded = num.decimalNumberByRoundingAccordingToBehavior(behaviour)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!