PeonProgrammer PeonProgrammer - 10 months ago 83
Swift Question

Which Swift datatype do I use for currency

I have an iOS application that will be performing a lot of basic arithmetic on numbers representing USD currency (eg 25.00 representing $25.00).

I have gotten into a lot of trouble using the datatype Double in other languages like Java and Javascript so I would like to know the best datatype to use for currency in Swift.


Use NSDecimalNumber (more info here). Example:

let a = NSDecimalNumber(integer: 123456)
let b = NSDecimalNumber(integer: 1000)
let c = a.decimalNumberByDividingBy(b)
// Result: "123.456"

You will probably want to use an extension like this one to add operator overloading to the NSDecimalNumber class.