Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round an NSDecimalNumber in swift?

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 like this:

NSDecimalNumber.decimalNumberByRoundingAccordingToBehavior(<#behavior: NSDecimalNumberBehaviors?#>)

It takes in an NSDecimalNumberBehavior, which I'm unsure how to manipulate since it (1) cannot be initiated into a variable and have it's properties changed, and (2) the roundingMode() method according to the documentation doesn't take any parameters, but Xcode fills in a parameter space for "self".

I'm totally lost on this. Back to the basic question; How can I round an NSDecimalNumber in swift?

Thanks in advance

like image 845
Naldhelaan Avatar asked Jun 26 '15 10:06

Naldhelaan


Video Answer


1 Answers

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))   
like image 85
Özgür Ersil Avatar answered Oct 09 '22 19:10

Özgür Ersil