Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift xcode string to decimal number

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()!

    }
}
like image 508
Jbr Avatar asked Jan 10 '23 10:01

Jbr


1 Answers

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
}
like image 186
Mario Hendricks Avatar answered Jan 12 '23 04:01

Mario Hendricks