I would like to convert text (such as "3.9") to a decimal number that can be used in mathematical formulas.
Here is the part of my code which allows me to convert integers, but I'd like to convert decimal numbers as well:
import UIKit
var xa = 0
class ViewController: UIViewController {
@IBOutlet weak var xA: UITextField!
@IBAction func chargecarte(sender: AnyObject) {
xa = xA.text.toInt()!
}
}
Using NumberFormatter is a good solution, here is an example on how to convert in Swift 3.0. Note that in Swift 3 NSNumberFormatter has been renamed NumberFormatter.
let formatter = NumberFormatter()
formatter.generatesDecimalNumbers = true
formatter.numberStyle = NumberFormatter.Style.decimal
if let formattedNumber = formatter.number(from: textValue) as? NSDecimalNumber {
xa = formattedNumber
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With