PeonProgrammer PeonProgrammer - 2 years ago 120
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download