Fotios Tragopoulos Fotios Tragopoulos - 1 year ago 181
Swift Question

Getting locale with NSNumberFormatter in iOS and Swift

I'm trying to make an application that receive the input from two UITextFields, multiplies them and gives back the product in a third UITextField.

import UIKit

class ParallelogramSurfaceArea: UIViewController {

@IBOutlet weak var sideA: UITextField!
@IBOutlet weak var height: UITextField!
@IBOutlet weak var surfaceArea: UITextField!

@IBAction func calculate(sender: AnyObject) {

let aText = (sideA.text! as NSString).doubleValue
let hText = (height.text! as NSString).doubleValue

let a = round(10000 * aText)/10000
let h = round(10000 * hText)/10000
let sa = round(10000*(a * h))/10000

sideA.text = "Side A = \(a) m"
height.text = "Height = \(h) m"
surfaceArea.text = "Surface Area = \(sa) m²"

The problem is that on the decimal pad the ',' appears instead of the '.' because of the locale settings resulting in an error in the calculation. How can I fix this with NSNumberFormatter? Any suggestions for improving the
class ParallelogramSurfaceArea

This question is marked as duplicate of this one but I can't see the similarities except for the similar topic.

Answer Source

If you want to convert from string to double and take in consideration the current local, NSNumberFormatter by default set the local value to the current locale by default

let numberFormatter = NSNumberFormatter()
numberFormatter.locale = NSLocale.currentLocale() // default value
// or custom local 
numberFormatter.locale = NSLocale(localeIdentifier: "fr_FR")

let stringValue  = sideA.text as? String ?? ""
let doubleValue  = numberFormatter.numberFromString(stringValue)?.doubleValue ?? 0.0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download