Convert String to Float in Swift
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)
Related videos on Youtube
Stephen Fox
Software Engineer from Dublin, Ireland. Github: https://github.com/StephenFox1995
Updated on March 12, 2021Comments
-
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
UITextfield
s 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 almost 10 yearsWell, 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 almost 10 years
wageConversionFloat
will never be the float, it crashes directly if the input string is a kind of float like234.56
. how could it be an accepted/upvoted solution...? -
rmaddy almost 10 yearsThis answer does not work if the text contains a decimal value. Example - this answer will return
3
if the text field has3.5
. This is because the text is first converted to anInt
, then theInt
is converted to aFloat
. -
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 almost 10 yearsAs great as this is, he was asking for
float
-
rayryeng almost 10 yearsExplain why this code works. This prevents copying and pasting without understanding of its operation.
-
sketchyTech over 9 yearsThe 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 over 9 years@GoodbyeStackOverflow, I am using Beta 4 and it definitely does not work. Maybe they changed it in Beta 5?
NSString
hasfloatValue
extension butString
does not. Get error:'String' does not have member named floatValue
-
sketchyTech over 9 yearsThis might be the reason. Also, do you have import Foundation at the top of your file?
-
Miles Works over 9 yearsactually it does work, with whole numbers, just not decimals. a decimal will throw a fatal error!
-
Carmen over 9 yearsbridgeToObjectiveC() was removed in Beta 5
-
Carmen over 9 yearsbridgeToObjectiveC() was removed in Beta 5
-
Carmen over 9 yearsBecause 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 almost 9 yearsI 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 almost 8 years
let floatValue = (Float)(Wage.text)
... In Swift 2.0 -
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 atelse if comps[0] == "" || comps[1] == ""
. Anyway you are so serious in conversion. -
TheTiger almost 8 years@PartiallyFrozenOJ But if condition was same in 2014 too. Anyway No problem!
-
Leo Dabus about 7 yearswhy not simply
return Float(self)
? -
JerryZhou over 6 yearsFor 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 about 6 yearsThis is the only correct answer for Swift 3 or later. You must use a
NumberFormatter
to deal with user entered floating point numbers. -
rmaddy about 6 yearsAs a general solution this should probably return a
Float?
and not treat invalid values as0.0
. Let the caller do something likelet val = field.floatValue ?? 0.0
if a given case should treat the bad result as zero. -
Rom over 5 yearsI 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 return0
if something is wrong.). Note thatNSNumberFormatter
was changedNumberFormatter
. -
Nirbhay Singh about 5 yearslet 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 over 3 yearsPlease add some explanations.
-
Elletlar over 3 years
-
prakash546 over 3 yearsgenerally 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.