Search code examples
swiftios9nsnumberformatter

How to store a price in two integers in swift


I have read that I shouldn't treat prices as double numbers and that I should store them as two integers.

If for example I have an input of type 246.464 in a UITextField how should I make it two integers?


Solution

  • Forget two integers, store it as NSDecimalNumber. That's the class specifically created for that task.

    Unlike float or double, NSDecimalNumber uses decadic arithmetic therefore there is no loss in precision when converting between decadic to binary and viceversa.

    let text = "246.464" // textField.text
    let number = NSDecimalNumber(string: text)