[string] Convert String to Float in Swift

I'm trying to convert numbers taken from a UITextField, which I presume, are actually Strings, and convert them to Float, so I can multiply them.

I have two UITextfields which are declared as follows:

@IBOutlet var wage: UITextField
@IBOutlet var hour: UITextField

When the user presses a UIButton I want to calculate the wages the user earns, but I can't, as I need to convert them to floats first, before I can use them.

I know how to convert them to an integer by doing this:

var wageConversion:Int = 0
wageConversion = wage.text.toInt()!

However, I have no idea how to convert them to floats.

This question is related to string floating-point swift string-parsing

The answer is


You have two options which are quite similar (by the approach and result):

// option 1:
var string_1 : String = "100"
var double_1 : Double = (string_1 as NSString).doubleValue + 99.0

// option 2: 
var string_2 : NSString = "100"
// or:  var string_2 = "100" as NSString
var number_2 : Double = string_2.doubleValue;

Swift 4/5, use just Float(value).

let string_value : String = "123200"

let float_value : Float = Float(string_value)

print(float_value)

Answer: 123200


This is how I approached it. I did not want to "cross the bridge", as it has been removed from Xcode 6 beta 5 anyway, quick and dirty:

extension String {

    // converting a string to double
    func toDouble() -> Double? {

        // split the string into components
        var comps = self.componentsSeparatedByString(".")

        // we have nothing
        if comps.count == 0 {
            return nil
        }
        // if there is more than one decimal
        else if comps.count > 2 {
            return nil
        }
        else if comps[0] == "" || comps[1] == "" {
            return nil
        }

        // grab the whole portion
        var whole = 0.0
        // ensure we have a number for the whole
        if let w = comps[0].toInt() {
            whole = Double(w)
        }
        else {
            return nil
        }

        // we only got the whole
        if comps.count == 1 {

            return whole

        }

        // grab the fractional
        var fractional = 0.0
        // ensure we have a number for the fractional
        if let f = comps[1].toInt() {

            // use number of digits to get the power
            var toThePower = Double(countElements(comps[1]))

            // compute the fractional portion
            fractional = Double(f) / pow(10.0, toThePower)

        }
        else {
            return nil
        }

        // return the result
        return whole + fractional
    }

    // converting a string to float
    func toFloat() -> Float? {

        if let val = self.toDouble() {
            return Float(val)
        }
        else {
            return nil
        }

    }

}


// test it out
var str = "78.001"

if let val = str.toFloat() {
    println("Str in float: \(val)")
}
else {
    println("Unable to convert Str to float")
}

// now in double
if let val = str.toDouble() {
    println("Str in double: \(val)")
}
else {
    println("Unable to convert Str to double")
}

Easy way:

// toInt returns optional that's why we used a:Int?
let a:Int? = firstText.text.toInt()
let b:Int? = secondText.text.toInt()

// check a and b before unwrapping using !
if a && b {
    var ans = a! + b!
    answerLabel.text = "Answer is \(ans)"
} else {
    answerLabel.text = "Input values are not numberic"
}

you can use same approach for other calculations, hope this help !!


In swift 4

let Totalname = "10.0" //Now it is in string

let floatVal  = (Totalname as NSString).floatValue //Now converted to float

Update

The accepted answer shows a more up to date way of doing

Swift 1

This is how Paul Hegarty has shown on Stanford's CS193p class in 2015:

wageConversion = NSNumberFormatter().numberFromString(wage.text!)!.floatValue

You can even create a computed property for not having to do that every time

var wageValue: Float {
        get {
            return NSNumberFormatter().numberFromString(wage.text!)!.floatValue
        }
        set {
            wage.text = "\(newValue)"
        }
    }

you can use,

let wg = Float(wage.text!)

If you want to round the float to 2 decimal places:

let wg = Float(String(format: "%.2f",wage.text!)

I found another way to take a input value of a UITextField and cast it to a float:

    var tempString:String?
    var myFloat:Float?

    @IBAction func ButtonWasClicked(_ sender: Any) {
       tempString = myUITextField.text
       myFloat = Float(tempString!)!
    }

Use this:

 // get the values from text boxes
    let a:Double = firstText.text.bridgeToObjectiveC().doubleValue
    let b:Double = secondText.text.bridgeToObjectiveC().doubleValue

//  we checking against 0.0, because above function return 0.0 if it gets failed to convert
    if (a != 0.0) && (b != 0.0) {
        var ans = a + b
        answerLabel.text = "Answer is \(ans)"
    } else {
        answerLabel.text = "Input values are not numberic"
    }

Using the accepted solution, I was finding that my "1.1" (when using the .floatValue conversion) would get converted to 1.10000002384186, which was not what I wanted. However, if I used the .doubleValue instead, I would get the 1.1 that I wanted.

So for example, instead of using the accepted solution, I used this instead:

var WageConversion = (Wage.text as NSString).doubleValue

In my case I did not need double-precision, but using the .floatValue was not giving me the proper result.

Just wanted to add this to the discussion in case someone else had been running into the same issue.


For the sake of completeness this is a solution using an extension of UITextField which can also consider a different locale.

For Swift 3+

extension UITextField {
    func floatValue(locale : Locale = Locale.current) -> Float {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        numberFormatter.locale = locale

        let nsNumber = numberFormatter.number(from: text!)
        return nsNumber == nil ? 0.0 : nsNumber!.floatValue
    }
}

Here is a Swift 3 adaptation of Paul Hegarty's solution from rdprado's answer, with some checking for optionals added to it (returning 0.0 if any part of the process fails):

var wageFloat:Float = 0.0

if let wageText = wage.text {
    if let wageNumber = NumberFormatter().number(from: wageText) {
        wageFloat = wageNumber.floatValue
    }
}

By the way, I took Stanford's CS193p class using iTunes University when it was still teaching Objective-C.

I found Paul Hegarty to be a FANTASTIC instructor, and I would highly recommend the class to anyone starting out as an iOS developer in Swift!!!


I convert String to Float in this way:

let numberFormatter = NSNumberFormatter()
let number = numberFormatter.numberFromString("15.5")
let numberFloatValue = number.floatValue

println("number is \(numberFloatValue)") // prints "number is 15.5"

extension String {    
    func floatValue() -> Float? {
        return Float(self)
    }
}

Because in some parts of the world, for example, a comma is used instead of a decimal. It is best to create a NSNumberFormatter to convert a string to float.

let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let number = numberFormatter.numberFromString(self.stringByTrimmingCharactersInSet(Wage.text))

Below will give you an optional Float, stick a ! at the end if you know it to be a Float, or use if/let.

let wageConversion = Float(wage.text)

to convert string to Float in Xcode 11 as previous methods need modification

func stringToFloat(value : String) -> Float {
    let numberFormatter = NumberFormatter()
    let number = numberFormatter.number(from: value)
    let numberFloatValue = number?.floatValue
    return numberFloatValue!
}

Works on Swift 5+

import Foundation

let myString:String = "50"
let temp = myString as NSString
let myFloat = temp.floatValue
print(myFloat)  //50.0
print(type(of: myFloat)) // Float

// Also you can guard your value in order to check what is happening whenever your app crashes.

guard let myFloat = temp.floatValue else {
fatalError(" fail to change string to float value.")
}

import Foundation
"-23.67".floatValue // => -23.67

let s = "-23.67" as NSString
s.floatValue // => -23.67

Double() builds an Double from an Int, like this:

var convertedDouble = Double(someInt)

Note that this will only work if your text actually contains a number. Since Wage is a text field, the user can enter whatever they want and this will trigger a runtime error when you go to unbox the Optional returned from toInt(). You should check that the conversion succeeded before forcing the unboxing.

if let wageInt = Wage.text?.toInt() {
    //we made it in the if so the conversion succeeded.
    var wageConversionDouble = Double(wageInt)
}

Edit:

If you're sure the text will be an integer, you can do something like this (note that text on UITextField is also Optional)):

if let wageText = Wage.text {
    var wageFloat = Double(wageText.toInt()!)
}

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to floating-point

Convert list or numpy array of single element to float in python Convert float to string with precision & number of decimal digits specified? Float and double datatype in Java C convert floating point to int Convert String to Float in Swift How do I change data-type of pandas data frame to string with a defined format? How to check if a float value is a whole number Convert floats to ints in Pandas? Converting Float to Dollars and Cents Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to string-parsing

Convert String to Float in Swift Parse time of format hh:mm:ss Counting the number of occurences of characters in a string How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern? How do I parse a URL query parameters, in Javascript? Convert String with Dot or Comma as decimal separator to number in JavaScript How do I extract a substring from a string until the second space is encountered? How to validate an email address using a regular expression?