How to round an NSDecimalNumber in swift?

前端 未结 3 745
予麋鹿
予麋鹿 2020-12-18 23:34

I can\'t find any resources on this, and I\'ve been trying all sorts of stuff, but nothing works.

According to Apple\'s documentation, you round an NSDecimalNumber l

相关标签:
3条回答
  • 2020-12-18 23:58

    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.

    0 讨论(0)
  • 2020-12-19 00:00
    // 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)
    
    0 讨论(0)
  • 2020-12-19 00:09

    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))   
    
    0 讨论(0)
提交回复
热议问题