swiftmaxnsdecimalnumber

Swift Round up / Max the NSDecimalNumber


Let's say we have an NSDecimal constant called total and it contains the value of 3.33333333 divided by 10/3. 10 and 3 are both NSDecimalNumber. We want the total to be 4 as an NSDecimalNumber in Swift.

let total = ten/three

// the ideal total would be rounded up whenever there is a floating 

in the doc. we have

func NSDecimalRound(_ result: UnsafeMutablePointer<NSDecimal>,
                  _ number: UnsafePointer<NSDecimal>,
                  _ scale: Int,
                  _ roundingMode: NSRoundingMode)


maximumDecimalNumber()

Which one is the best fit for calculator with currency style? Please include an example each how to use them if you know so. Thank you .


Solution

  • let x = NSDecimalNumber(string:"10")
    let y = NSDecimalNumber(string:"3")
    let total = x.decimalNumberByDividingBy(y).decimalNumberByRoundingAccordingToBehavior( NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundUp, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false))   // 4