Reputation: 4506
I am writing a Swift app and am dealing with decimals in a database (stored in mysql as decimals, with 2 digits. Basically it's sales someone made each day, so generally anything from $0 to $1000, but not millions, and nothing insane in terms of trailing decimals, just always rounded to 2 decimal places).
Referencing this helped me out: How to properly format currency on ios
..But I wanted to just do a quick sanity check here and make sure this strategy is ok. i.e I would use NSDecimal or NSDecimalNumber (is there a preferred swift equivalent??)
What would you all recommend I do when dealing with currency in Swift? I'd like to use the locale-based currency symbol as well. I have a class called Sales that contains the amount in question. What do you recommend the datatype to be?
Apologies if I am coming off lazy, I actually have some ideas on what to do but feel a little overwhelmed at the "right" approach, especially in a locale-sensitive way, and wanted to check in here with you all.
Thanks so much!
Upvotes: 13
Views: 16345
Reputation: 118651
Update for Swift 3: A Decimal
type is now available with built-in support for operators like *
, /
, +
, <
, etc. When used in an Any context (passed to Objective-C), it's bridged to NSDecimalNumber
.
Old answer:
NSDecimal
is not really supported in Swift (it's a weird opaque pointer type), but NSDecimalNumber
is — and as in Obj-C, it's the best thing to use for base-ten arithmetic (because it actually does its operations in base ten). NSLocale
, NSNumberFormatter
and friends all work too and should satisfy your localization needs.
Upvotes: 12
Reputation: 689
Swift 3 now has a Decimal (value) type which is bridged to NSDecimalNumber.
Upvotes: 3