Convert String to Float in Swift

146,631

Solution 1

Swift 2.0+

Now with Swift 2.0 you can just use Float(Wage.text) which returns a Float? type. More clear than the below solution which just returns 0.

If you want a 0 value for an invalid Float for some reason you can use Float(Wage.text) ?? 0 which will return 0 if it is not a valid Float.


Old Solution

The best way to handle this is direct casting:

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

I actually created an extension to better use this too:

extension String {
    var floatValue: Float {
        return (self as NSString).floatValue
    }
}

Now you can just call var WageConversion = Wage.text.floatValue and allow the extension to handle the bridge for you!

This is a good implementation since it can handle actual floats (input with .) and will also help prevent the user from copying text into your input field (12p.34, or even 12.12.41).

Obviously, if Apple does add a floatValue to Swift this will throw an exception, but it may be nice in the mean time. If they do add it later, then all you need to do to modify your code is remove the extension and everything will work seamlessly, since you will already be calling .floatValue!

Also, variables and constants should start with a lower case (including IBOutlets)

Solution 2

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

Solution 3

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"

Solution 4

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)"
        }
    }

Solution 5

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)
Share:
146,631

Related videos on Youtube

Stephen Fox
Author by

Stephen Fox

Software Engineer from Dublin, Ireland. Github: https://github.com/StephenFox1995

Updated on March 12, 2021

Comments

  • Stephen Fox
    Stephen Fox about 3 years

    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.

  • Stephen Fox
    Stephen Fox almost 10 years
    Well, I am only allowing the user to enter in numbers as the keypad is a Decimal Pad, so they can't actually enter in anything other than numbers.
  • holex
    holex almost 10 years
    wageConversionFloat will never be the float, it crashes directly if the input string is a kind of float like 234.56. how could it be an accepted/upvoted solution...?
  • rmaddy
    rmaddy almost 10 years
    This answer does not work if the text contains a decimal value. Example - this answer will return 3 if the text field has 3.5. This is because the text is first converted to an Int, then the Int is converted to a Float.
  • rmaddy
    rmaddy almost 10 years
    @StephenFox Keep in mind that a user can paste non-numeric text into the text field or the user may have an external keyboard. Never rely on just the keyboard to ensure data entry.
  • Jack
    Jack almost 10 years
    As great as this is, he was asking for float
  • rayryeng
    rayryeng almost 10 years
    Explain why this code works. This prevents copying and pasting without understanding of its operation.
  • sketchyTech
    sketchyTech over 9 years
    The extension isn't required, the bridge is done automatically by Swift, as @tom states all you need is Wage.text.floatValue. Not sure whether this changed between the answer being posted and now, but it's been there for a while.
  • Firo
    Firo over 9 years
    @GoodbyeStackOverflow, I am using Beta 4 and it definitely does not work. Maybe they changed it in Beta 5? NSString has floatValue extension but String does not. Get error: 'String' does not have member named floatValue
  • sketchyTech
    sketchyTech over 9 years
    This might be the reason. Also, do you have import Foundation at the top of your file?
  • Miles Works
    Miles Works over 9 years
    actually it does work, with whole numbers, just not decimals. a decimal will throw a fatal error!
  • Carmen
    Carmen over 9 years
    bridgeToObjectiveC() was removed in Beta 5
  • Carmen
    Carmen over 9 years
    bridgeToObjectiveC() was removed in Beta 5
  • Carmen
    Carmen over 9 years
    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. Look at @DmitriFuerle Answer
  • User
    User almost 9 years
    I don't consider this very safe, at least for Swift standards, since if the string is not a number, NSString.floatValue just returns 0. This should trigger an Exception or at least return nil.
  • TheTiger
    TheTiger almost 8 years
    let floatValue = (Float)(Wage.text) ... In Swift 2.0
  • TheTiger
    TheTiger almost 8 years
    @PartiallyFrozenOJ Have you tried toDouble() function with "10" string I mean if there is no decimal. It will crash anyway. Because in that case count will be 1 and you are not handling that. It will crash at else if comps[0] == "" || comps[1] == "" . Anyway you are so serious in conversion.
  • TheTiger
    TheTiger almost 8 years
    @PartiallyFrozenOJ But if condition was same in 2014 too. Anyway No problem!
  • Leo Dabus
    Leo Dabus about 7 years
    why not simply return Float(self) ?
  • JerryZhou
    JerryZhou over 6 years
    For the float string of "12,3" in German, Float("12,3") = nil not work, ("12,3" as? NSString)?.floatValue = Optional(12.0) also not good.
  • rmaddy
    rmaddy about 6 years
    This is the only correct answer for Swift 3 or later. You must use a NumberFormatter to deal with user entered floating point numbers.
  • rmaddy
    rmaddy about 6 years
    As a general solution this should probably return a Float? and not treat invalid values as 0.0. Let the caller do something like let val = field.floatValue ?? 0.0 if a given case should treat the bad result as zero.
  • Rom
    Rom over 5 years
    I think this is the best solution (at least for swift 4+), the main reason being that it returns an optional (as opposed to NSString.floatValue, which simply return 0 if something is wrong.). Note that NSNumberFormatter was changed NumberFormatter.
  • Nirbhay Singh
    Nirbhay Singh about 5 years
    let a = Float32("45.6") will return the Float value from the string in Swift 4.2. Even we can also use Float64() method for the same.
  • Paul Floyd
    Paul Floyd over 3 years
    Please add some explanations.
  • Elletlar
    Elletlar over 3 years
  • prakash546
    prakash546 over 3 years
    generally changing String directly to float value fails. so first we have to change it into NS string and then to float. this way xcode also becomes happy lol.